字符串插值内部的字符串插值
问题描述:
是否有可能需要插值的字符串格式的变量。字符串插值内部的字符串插值
public class Setting
{
public string Format { get; set; }
}
var setting = new Setting { Format = "The car is {colour}" };
var colour = "black";
var output = $"{setting.Format}";
预计输出
“的车是黑色的。”
答
你不能那样做。字符串插值是纯粹的编译时功能。
答
你可以做轻微的改动就可以了,如下所示:
public class Setting
{
public string Format
{
get
{
return String.Format(this.Format, this.Colour);
}
set
{
Format = value;
}
}
public string Colour { get; set; }
}
var setting = new Setting { Format = "The car is {0}", Colour = "black" };
然后输出将是“汽车是黑色的。”
我还没有测试过这段代码。
答
不,你不能这样做,但你可以实现与一个稍微不同的方式是相同的,那我来想:
public class Setting
{
public Func<string, string> Format { get; set; }
}
,那么你可以通过你的字符串参数Format
:
var setting = new Setting { Format = s => $"The car is {s}" };
var output = setting.Format("black");
+0
编译器基本上变成了'设置{Format = s => string.Format(“汽车是{0}”,s)};' –
答
为什么不呢?
首先,你不能在使用C#声明它之前使用局部变量。所以 在使用之前首先声明colour
。然后“插入”分配给Format
的字符串,就完成了。
var colour = "black";
var setting = new Setting { Format = $"The car is {colour}" };
var output = $"{setting.Format}";
Console.WriteLine(output);
输出:
的车是黑色的。
+0
我喜欢这个,但是你可以为未来的读者详细说明,因为你的改变是如此微妙? –
使用'string.Format'。如果你有变量而不是常量。你不能吃你的蛋糕,也不能吃。 –
人们为此写了一堆扩展方法。 ['FormatWith'](http://james.newtonking.com/archive/2008/03/29/formatwith-2-0-string-formatting-with-named-variables)或类似的。要警告的是,这些自定义函数中的每一个都有[稍微不同的行为](https://web.archive.org/web/20131203044747/http://blog.dotnetwiki.org/2009/01/16/NamedFormatsPexTestimonium.aspx) 。另见[命名格式Redux](http://haacked.com/archive/2009/01/14/named-formats-redux.aspx/)。 – Brian