用于多行插值的C#FormattableString串联

用于多行插值的C#FormattableString串联,c#,string-concatenation,formattablestring,C#,String Concatenation,Formattablestring,在C#7中,我尝试使用多行插值字符串来与一起使用,但字符串串联对于FormttableString似乎无效 根据:FormattableString实例可能来自C#或Visual Basic中的插值字符串 未编译以下FormttableString多行连接: using static System.FormattableString; string build = Invariant($"{this.x}" + $"{this.y}"

在C#7中,我尝试使用多行插值字符串来与一起使用,但字符串串联对于FormttableString似乎无效

根据:FormattableString实例可能来自C#或Visual Basic中的插值字符串

未编译以下FormttableString多行连接:

using static System.FormattableString;
string build = Invariant($"{this.x}" 
                       + $"{this.y}"
                       + $"$this.z}");
错误CS1503-参数1:无法从“字符串”转换为 'System.FormattableString'

使用不带串联的插值字符串不会编译:

using static System.FormattableString;
string build = Invariant($"{this.x}");
如何使用
FormattableString
类型实现多行字符串连接


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

不变方法需要参数
FormattableString
。 在您的例子中,参数
$“{this.x}”+$“{this.y}”
将变成
“string”+“string”
,它将计算为
字符串
类型输出。这就是您得到编译错误的原因,因为
不变量
预期的是
FormattableString
,而不是
字符串

对于单行文本,您应该尝试使用此选项-

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,然后使用不变量

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

这是X

这是我的

这是Z


你能提供它无法编译的原因吗?@John,已经添加了错误代码。$“{this.x}“是一个字符串,字符串插值只是字符串格式的一种语法糖,在本例中,它不起任何作用,它与使用
this.x
”相同,您正在尝试传递字符串,而FormattableString是预期的,错误消息告诉您you@SelmanGenç-非连接的插值字符串工作正常。根据:FormattableString实例可能来自C#或Visual Basic中的插值字符串。是,但您正在尝试连接两个插值字符串,这两个字符串的计算结果将为string not FormattableString,更新后的答案。如何将多行连接的插值字符串实现为
FormattableString
?连接插值字符串以用作
FormattableString
的正确方法是什么?更新了我的答案,现在是多线性连接。