问题在于,C#中的
string interpolation只是对
string.Format
的语法糖包装。这些字符串会被编译成相同的代码。以这段代码为例:
public string GetGreeting1(string name)
{
return string.Format("Hello {0}!", name);
}
public string GetGreeting2(string name)
{
return $"Hello {name}!";
}
两种方法的IL输出相同:
GetGreeting1:
IL_0000: ldstr "Hello {0}!"
IL_0005: ldarg.1
IL_0006: call System.String.Format
IL_000B: ret
GetGreeting2:
IL_0000: ldstr "Hello {0}!"
IL_0005: ldarg.1
IL_0006: call System.String.Format
IL_000B: ret
所以,您提供的解决方案是完全有效的,我之前也使用过。唯一可能的改进是,如果您打算进行大量替换,那么如果切换到使用
StringBuilder
,您可能会发现性能有所提升。您可能可以在 Nuget 上找到一个库来为您完成这个操作,但这可能只是为了您的目的而过度了。
作为额外的内容,我创建了一个扩展类。额外的奖励是,我还添加了一个使用反射来进行替换的具有任意数量参数的对象方法:
public static class StringReplacementExtensions
{
public static string Replace(this string source, Dictionary<string, string> values)
{
return values.Aggregate(
source,
(current, parameter) => current
.Replace($"{{{parameter.Key}}}", parameter.Value));
}
public static string Replace(this string source, object values)
{
var properties = values.GetType().GetProperties();
foreach (var property in properties)
{
source = source.Replace(
$"{{{property.Name}}}",
property.GetValue(values).ToString());
}
return source;
}
}
并且使用方法如下:
var source = "Hello {name}!";
var dict = new Dictionary<string, string> { { "name", "David" } };
var greeting1 = source.Replace(dict);
Console.WriteLine(greeting1);
var greeting2 = source.Replace(new { name = "David" });
Console.WriteLine(greeting2);
string.Format
的语法糖,你不能像这样使用预设的字符串。 - DavidGString.Replace
。有没有其他方法? - Unbreakable