您可以使用System.FormattableString
或System.IFormattable
类:
IFormattable ifs = (IFormattable)$"Hello, {name}";
System.FormattableString fss = $"Hello, {name}";
// pass null to use the format as it was used upon initialization above.
string ifresult = ifs.ToString(null, CultureInfo.InvariantCulture);
string fsresult = fss.ToString(CultureInfo.InvariantCulture);
您需要编译针对Framework 4.6的版本,因为 IFormattable
和 FormattableString
这两个类在旧版本中不存在。所以,如果您的目标是更早的 .NET framework 版本,则无法使用插值语法而不触发错误。
除非您使用一个小技巧 (改编自Jon Skeet的gist,并编译针对4.6 RTM,以及从我的帐户派生出去的 )。只需将一个包含以下内容的类文件添加到您的项目中:
Update
There is now also a Nuget package available that will provide the same functionality to your project (thanks for bringing this to my attention @habakuk).
install-package StringInterpolationBridge
如果您不想在产品中添加额外的程序集,但又希望实现相同的功能,请将以下代码添加到您的项目中:
namespace System.Runtime.CompilerServices
{
internal class FormattableStringFactory
{
public static FormattableString Create(string messageFormat, params object[] args)
{
return new FormattableString(messageFormat, args);
}
}
}
namespace System
{
internal class FormattableString : IFormattable
{
private readonly string messageFormat;
private readonly object[] args;
public FormattableString(string messageFormat, object[] args)
{
this.messageFormat = messageFormat;
this.args = args;
}
public override string ToString()
{
return string.Format(messageFormat, args);
}
public string ToString(string format, IFormatProvider formatProvider)
{
return string.Format(formatProvider, format ?? messageFormat, args);
}
public string ToString(IFormatProvider formatProvider)
{
return string.Format(formatProvider, messageFormat, args);
}
}
}
请参考: