带有变量文本的多行字符串

时间:2013-04-24 15:09:26

标签: c#

我知道这会奏效:

string multiline_text = @"this is a multiline text
this is line 1
this is line 2
this is line 3";

如何进行以下工作:

string a1 = " line number one";
string a2 = " line number two";
string a3 = " line number three";

string multiline_text = @"this is a multiline text
this is " + a1 + " 
this is " + a2 + " 
this is " + a3 + ";

是否可以不将字符串拆分为多个子字符串,每行一个?

7 个答案:

答案 0 :(得分:58)

一种选择是使用字符串格式。在C#6之前:

string pattern = @"this is a multiline text
this is {0}
this is {1}
this is {2}";

string result = string.Format(pattern, a1, a2, a3);

使用C#6,您可以使用插值的逐字字符串文字:

string pattern = $@"this is a multiline text
this is {a1}
this is {a2}
this is {a3}";

请注意,$@必须完全相同 - 如果您尝试使用@$,则无法编译。

答案 1 :(得分:7)

虽然string.Format是更好的做法,但为了做你想要实现的目标,只需在每行的末尾添加额外的@

string multiline_text = @"this is a multiline text
this is " + a1 + @" 
this is " + a2 + @" 
this is " + a3 + @"";

在结束分号前你也错过了最后一个"

答案 2 :(得分:5)

您可以从StringBuilder类获得这样的可读性:

StringBuilder sb = new StringBuilder();
sb.AppendLine("this is a multiline");
sb.AppendLine("this is " + a1); // etc

var result = sb.ToString();

答案 3 :(得分:4)

使用Visual Studio 2015,您可以编写:

string multiline_text = $@"this is a multiline text
this is {a1}
this is {a2}
this is {a3}";

String.Format将由编译器使用(如在Jons的答案中),但它更容易阅读。

答案 4 :(得分:1)

由于某些原因,c#不支持这样的多行文本。你最接近的是:

string a1 = " line number one";
string a2 = " line number two";
string a3 = " line number three";

string multiline_text = @"this is a multiline text" +
"this is " + a1 +
"this is " + a2 +
"this is " + a3;

答案 5 :(得分:0)

为了好玩,您还可以使用数组连接技术来获取可读内容并控制缩进。有时迫使你完全左对齐的多行模板是难看的......

Year Max =
    VAR CalculatedTable = SUMMARIZECOLUMNS(FactForwardLookingAccumulation[Year], "Losses By Year", SUM(FactForwardLookingAccumulation[Net Loss Our Share Usd]))
    RETURN MAXX(CalculatedTable, [Losses By Year])

如果必须格式化,请将连接包装为整齐的结果而不是单独的行。

答案 6 :(得分:-1)

另一个可能的解决方案是Jon Skeet的回答:

string result = string.Format(
    "this is a multiline text{0}this is {1}{0}this is {2}{0}this is {3}",
    Environment.NewLine, a1, a2, a3);

所以基本上你要插入一个新行,你想要一个{0}。由于这个原因,它使字符串更抽象,但这个解决方案的好处是它完全封装在string.Format方法中。它可能不是那么相关 - 但值得一提。