C#中的FormattableString用于多行插值的拼接

18
在C#7中,我试图使用多行插值字符串与FormttableString.Invariant一起使用,但是字符串连接似乎对FormttableString无效。
根据文档:FormattableString实例可能来自C#或Visual Basic中的插值字符串。
以下FormttableString多行连接不会编译:
using static System.FormattableString;
string build = Invariant($"{this.x}" 
                       + $"{this.y}"
                       + $"$this.z}");

使用插值字符串而不进行连接是无法编译的:{{错误 CS1503-参数1:无法将"string"转换为"System.FormattableString"}}。
使用插值字符串进行连接是可以编译的:
using static System.FormattableString;
string build = Invariant($"{this.x}");

你如何使用FormattableString类型实现多行字符串连接?

(请注意,FormattableString是在.NET Framework 4.6中添加的。)


1
你能够包含提供的原因为什么它无法编译吗? - ProgrammingLlama
@John,错误代码已添加。 - Eugene
$"{this.x}" 是一个字符串,字符串插值仅仅是对字符串格式化的一种语法糖,而在这个例子中它没有做任何事情,和使用 this.x 是一样的。你正在尝试传递一个字符串,但是错误消息告诉你需要一个可格式化的字符串(FormattableString)。 - Selman Genç
1
@SelmanGenç - 一个非连接的插值字符串可以正常工作。 - Eugene
1个回答

15
Invariant方法期望传入type的FormattableString参数。在您的情况下,参数$"{this.x}" + $"{this.y}"变成了"string" + "string',这将计算为string类型输出。这就是为什么您会收到编译错误的原因,因为Invariant期望传入FormattableString而不是string。
对于单行文本,您应该尝试这个 -
public string X { get; set; } = "This is X";
public string Y { get; set; } = "This is Y";
public string Z { get; set; } = "This is Z";
string build = Invariant($"{this.x} {this.y} {this.z}");

输出 -

这是X 这是Y 这是Z

要实现多行插值,您可以构建下面的FormattableString,然后使用Invarient。

FormattableString fs = $@"{this.X}
{this.Y}
{this.Z}";
string build = Invariant(fs);

输出 -

这是 X

这是 Y

这是 Z


根据文档:FormattableString实例可以来自于C#或Visual Basic中的插值字符串。 - Eugene
是的,但您正在尝试连接2个插值字符串,这将评估为字符串而不是FormattableString,已更新答案。 - Vinit
你如何实现一个多行连接的插值字符串作为FormattableString?什么是连接插值字符串以用作FormattableString的正确方式? - Eugene
1
更新了我的答案,现在可以进行多行连接。 - Vinit

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接