用于多行插值的 C# FormattableString 连接 [英] C# FormattableString concatenation for multiline interpolation
问题描述
在 C#7 中,我尝试使用多行内插字符串与 FormttableString.Invariant 但字符串连接似乎对 FormttableString 无效.
根据文档:FormattableString 实例可能由 C# 或 Visual Basic 中的内插字符串产生.
以下 FormttableString 多行连接无法编译:
使用静态 System.FormattableString;string build = Invariant($"{this.x}"+ $"{this.y}"+ $"$this.z}");
<块引用>
错误 CS1503 - 参数 1:无法从字符串"转换为'System.FormattableString'
使用没有连接的内插字符串确实可以编译:
使用静态 System.FormattableString;string build = Invariant($"{this.x}");
如何使用 FormattableString
类型实现 多行 字符串连接?
(请注意 FormattableString 是在 .Net Framework 4.6 中添加的.)
Invariant 方法需要 FormattableString
的参数 type.在您的情况下,参数 $"{this.x}"+ $"{this.y}"
变成 "string";+ "string'
将评估为 string
类型的输出.这就是您收到编译错误的原因,因为 Invariant
需要 FormattableString
而不是 string
.
对于单行文本你应该试试这个 -
public string X { get;放;} = "这是 X";公共字符串 Y { 得到;放;} = "这是 Y";公共字符串 Z { 得到;放;} =这是Z";string build = Invariant($"{this.x} {this.y} {this.z}");
输出 -
<块引用>这是X 这是Y 这是Z
为了实现multiline
插值,你可以像下面这样构建FormattableString,然后使用Invarient.
FormattableString fs = $@"{this.X}{这个.Y}{this.Z}";字符串构建 = 不变(fs);
输出 -
<块引用>这是X
这是Y
这是Z
In C#7, I'm trying to use a multiline interpolated string for use with FormttableString.Invariant but string concatenation appears to be invalid for FormttableString.
Per the documentation: A FormattableString instance may result from an interpolated string in C# or Visual Basic.
The following FormttableString multiline concatenation does not compile:
using static System.FormattableString;
string build = Invariant($"{this.x}"
+ $"{this.y}"
+ $"$this.z}");
Error CS1503 - Argument 1: cannot convert from 'string' to 'System.FormattableString'
Using an interpolated string without concatenation does compile:
using static System.FormattableString;
string build = Invariant($"{this.x}");
How do you implement multiline string concatenation with the FormattableString
type?
(Please note that FormattableString was added in .Net Framework 4.6.)
The Invariant method is expecting the parameter of FormattableString
type.
In your case, the parameter $"{this.x}" + $"{this.y}"
becomes "string" + "string'
which will evaluate to string
type output. That's the reason you are getting the compile error as Invariant
is expecting the FormattableString
and not string
.
You should try this for single line text -
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}");
Output -
This is X This is Y This is Z
And to implement multiline
interpolation, you can build the FormattableString like below and then use the Invarient.
FormattableString fs = $@"{this.X}
{this.Y}
{this.Z}";
string build = Invariant(fs);
Output -
This is X
This is Y
This is Z
这篇关于用于多行插值的 C# FormattableString 连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!