【问题标题】:Weird Result of String字符串的奇怪结果
【发布时间】:2014-11-19 08:22:14
【问题描述】:

只是好奇而已。我想知道为什么:

string str = @"//
    // Use a new char[] array of two characters (\r and \n) to break
    // lines from into separate strings. \n Use RemoveEmptyEntries
    // to make sure no empty strings get put in the string array. 
    //";

richTextBox 的结果文本是:

//
    // Use a new char[] array of two characters (\r and \n) to break
    // lines from into separate strings. \n Use RemoveEmptyEntries
    // to make sure no empty strings get put in the string array. 
    //

但是

string str = @"//
    // Use a new char[] array of two characters (\r and \n) to break
    // lines from into separate strings."+" \n" + @" Use RemoveEmptyEntries
    // to make sure no empty strings get put in the string array. 
    //";

richTextBox 的结果文本是:

//
    // Use a new char[] array of two characters (\r and \n) to break
    // lines from into separate strings. 
 Use RemoveEmptyEntries
    // to make sure no empty strings get put in the string array. 
    //

【问题讨论】:

    标签: c# string newline richtextbox


    【解决方案1】:

    在你的中心字符串“\n”之前没有文字@ 相当于

    string str = @"//
    // Use a new char[] array of two characters (\r and \n) to break
    // lines from into separate strings."+ @" \n" + @" Use RemoveEmptyEntries
    // to make sure no empty strings get put in the string array. 
    //";
    

    \ 是普通字符串中的转义字符,但字符串文字完全按原样使用内容,除了 " 被转义为 ""

    【讨论】:

    • @Elegiac 不会。它将“\n”读取为一个简单的字符串,但如果没有@,它也会在其中找到转义序列。
    【解决方案2】:

    因为在第二个示例中的“\n”之前没有@。 @(逐字字符串文字)之后的任何转义序列都将被忽略。在您的第一个示例中,它被忽略了,但在第二个示例中没有。

    看看这个: http://msdn.microsoft.com/en-us/library/aa691090(v=vs.71).aspx

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-03
      • 2023-03-08
      • 1970-01-01
      相关资源
      最近更新 更多