37

我知道这会起作用:

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 + ";

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

4

7 回答 7

96

One option is to use string formatting instead. Before 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);

With C# 6, you can use an interpolated verbatim string literal:

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

Note that $@ has to be exactly that - if you try to use @$, it won't compile.

于 2013-04-24T15:10:36.850 回答
7

虽然string.Format是更好的做法,但要完成您想要实现的目标,只需@在每行末尾添加额外的 s :

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

您还缺少"结束分号之前的最后一个。

于 2013-04-24T15:12:12.960 回答
5

您可以从StringBuilder课程中获得这样的可读性:

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

var result = sb.ToString();
于 2013-04-24T15:11:11.853 回答
4

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

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

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

于 2015-12-09T23:43:19.670 回答
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;
于 2013-04-24T15:11:48.953 回答
0

按照 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方法中。这可能不是那么相关——但值得一提。

于 2013-04-24T15:12:43.403 回答
0

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

string a1 = "London", a2 = "France", a3 = "someone's underpants";

string result = string.Join(Environment.NewLine, new[] {
    $"this is {a1}", // interpolated strings look nice
    "this is " + a2, // you can concat if you can't interpolate
    $"this is {a3}"  // these in-line comments can be nice too
});

如果您必须格式化,请包装连接以获得整洁的结果,而不是单独的行。

于 2018-02-27T22:41:45.310 回答