高效的模板人口

spe*_*der 9 c# string templates

假设我有一个文本模板,其中包含许多需要填充的字段:

var template = "hello {$name}. you are {$age} years old. you live in {$location}"
Run Code Online (Sandbox Code Playgroud)

以及IDictionary<string,string>要替换的值:

key     | value
===================
name    | spender
age     | 38
location| UK
Run Code Online (Sandbox Code Playgroud)

填充模板的天真方式可能是这样的:

var output = template;
foreach(var kvp in templValues)
{
    output = output.Replace(string.format("{{${0}}}", kvp.Key), kvp.Value);
}
Run Code Online (Sandbox Code Playgroud)

然而,这看起来非常低效.有没有更好的办法?

Nuf*_*fin 4

您可以使用Regex.Replace(),如下所示:

var output = new Regex(@"\{\$([^}]+)\}").Replace(
    template,
    m => templValues.ContainsKey(m.Captures[1].Value)
        ? templValues[m.Captures[1].Value]
        : m.Value);
Run Code Online (Sandbox Code Playgroud)

AFAIK 如果你的字典是这样构建的,这也可以防止意外的结果,因为这可能会产生"hello UK. you are 38 years old. you live in UK"and "hello {$location}. you are 38 years old. you live in UK",因为字典不会对它们的键进行排序:

key     | value
===================
name    | {$location}
age     | 38
location| UK
Run Code Online (Sandbox Code Playgroud)

当确实需要第一个行为时,您可以多次运行正则表达式。

编辑:如果模板解析实际上位于代码的时间关键部分,不要在那里进行模板解析。您应该考虑使用Sean推荐的手动解析方法。