【问题标题】:How to put a new line inside a string in C# source code?如何在 C# 源代码中的字符串中添加新行?
【发布时间】:2009-01-21 12:13:31
【问题描述】:

C# 语法中是否有定义新行的方法? (就像在 VB 中一样 _ )

例子:

代替:

string myStr = "very long string" +
"another long string";

这个:

string myStr = "very long string \something
another long string"

或者;编译器是否处理这个并做类似的事情; "string" + "string" -> 在这个例子中是 "stringstring"?

欢迎使用不同的情况,例如这些字符串是常量等。

【问题讨论】:

    标签: c# syntax


    【解决方案1】:

    编译器将 "ABC" + "DEF" 转换为 "ABCDEF",因此使用 + 是没有成本的

    【讨论】:

    • 这看起来很有趣,所以当我们知道所有字符串时,就不需要使用StringBuilder了吗?像 sb.Append("long str"); sb.Append("long str");相反,只需写“long str”+“long str”或@“long str ...”
    • erdogany:完全正确。另外,"this" + 1 + "string" 在编译时被转换为"this 1 string"。
    • @DrJokepu:你确定吗?
    • 当字符串在编译时已知时,编译器会将串联替换为单个字符串。您可以通过创建一个简单的类并使用 ildasm 查看程序集来轻松检查这一点。
    • 之所以有效,是因为所有被连接的字符串元素在编译时都是已知的。
    【解决方案2】:

    你可以使用

    string myStr = @"very long string
    another long string";
    

    @" 是字符串文字的开头,这种字符串在找到下一个 " 字符之前不会结束。

    c# 没有与 vb 中的 _ 字符相同的确切语法。因此,如果您想避免包含新行,则必须手动将字符串连接到不同的行。

    【讨论】:

    • 没错,但您必须注意不要缩进第二行。否则,空格(空格或制表符)将成为结果字符串的一部分。
    • 哦,换行符也将成为结果字符串的一部分。
    • “哦,换行符也将成为结果字符串的一部分”,是的,这不好。对我来说没什么大不了的,但是这不能像 VB 中的 _ 那样做。
    • 这是错误的答案 - 答案只是使用第一个代码 sn-p 因为编译器连接文字。
    【解决方案3】:

    我相信您正在寻找的是 C# 行继续符。

    别找了。空无一人。在 C# 中,一行以分号“;”结束到达。

    因此,正如其他人所提到的,如果您想拆分字符串分配,只需使用“+”字符。

    
    namespace Jaberwocky
    {
        class Program
        {
            public static void Main(string[] args)
            {
                string s = "Hello World! " +
                    "This is a long string " +
                    "That continues on and " +
                    "on and on and on.";
                Console.WriteLine(s);
                Console.ReadKey(true);
            }
        }
    }
    

    【讨论】:

      【解决方案4】:

      应尽可能使用 StringBuilder 来连接字符串,因为它比简单地使用 "this" + "that" 运行得更快。

      【讨论】:

      • StringBuilder 对于固定或已知的少量字符串连接来说太过分了。
      猜你喜欢
      • 2016-02-26
      • 1970-01-01
      • 2013-06-27
      • 2016-03-09
      • 1970-01-01
      • 2011-05-06
      • 2011-04-14
      • 1970-01-01
      • 2021-10-02
      相关资源
      最近更新 更多