[英]C# FormattableString concatenation for multiline interpolation
在 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:無法從“字符串”轉換為“System.FormattableString”
使用沒有連接的插值字符串可以編譯:
using static System.FormattableString;
string build = Invariant($"{this.x}");
如何使用FormattableString
類型實現多行字符串連接?
(請注意 FormattableString 是在 .Net Framework 4.6 中添加的。)
Invariant 方法需要FormattableString
類型的參數。 在您的情況下,參數$"{this.x}" + $"{this.y}"
變為"string" + "string'
這將評估為string
類型 output。這就是您收到編譯錯誤為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}");
Output -
這是X 這是Y 這是Z
要實現multiline
線插值,您可以像下面那樣構建 FormattableString,然后使用 Invarient。
FormattableString fs = $@"{this.X}
{this.Y}
{this.Z}";
string build = Invariant(fs);
Output -
這是X
這是Y
這是Z
Olá eu estava com essa necessidade e consegui desta maneira。
FormattableString colunaUpdate = $"";
FormattableString separador = $", ";
foreach (var item in lista[0].substituirRegistros)
{
separador = $", ";
if (colunaUpdate.ToString() == "")
{
separador = $"";
}
colunaUpdate = $"{colunaUpdate}{separador}{item.Field_Atualizar:C}={item.Field_Atualizar:P}";
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.