您将使用 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 框架,你不能在不触发错误的情况下使用插值语法。
除非您应用一点技巧(adapted to compile against 4.6 RTM from Jon Skeet's gist 和 forked to my own account.)。只需将一个类文件添加到您的项目中,其中包含:
更新
现在还有一个Nuget package available that will provide the same functionality to your project(感谢@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);
}
}
}
见: