Csharp/C#教程:延迟模板字符串插值分享


延迟模板字符串插值

在C#中有一个字符串插值支持,如下所示:

$"Constant with {Value}" 

这将使用范围内变量Value格式化此字符串。

但是以下内容不能用当前的C#语法编译。

说,我有一个静态的Dictionary模板:

 templates = new Dictionary { { "Key1", $"{Value1}" }, { "Key2", $"Constant with {Value2}" } } 

然后在这个方法的每次运行中我想填写占位符:

 public IDictionary FillTemplate(IDictionary placeholderValues) { return templates.ToDictionary( t => t.Key, t => string.FormatByNames(t.Value, placeholderValues)); } 

如果不对这些占位符进行正则表达式解析,然后在该正则表达式上替换回调,是否可以实现? 什么是最适合这种方法的高性能选项?

例如,它在Python中很容易实现:

 >>> templates = { "Key1": "{Value1}", "Key2": "Constant with {Value2}" } >>> values = { "Value1": "1", "Value2": "example 2" } >>> result = dict(((k, v.format(**values)) for k, v in templates.items())) >>> result {'Key2': 'Constant with example 2', 'Key1': '1'} >>> values2 = { "Value1": "another", "Value2": "different" } >>> result2 = dict(((k, v.format(**values2)) for k, v in templates.items())) >>> result2 {'Key2': 'Constant with different', 'Key1': 'another'} 

使用基于正则表达式进行替换的扩展方法,我可以快速地为每个值使用多个Replace调用。

这是扩展大括号包围变量的扩展方法:

 public static class ExpandExt { static Regex varPattern = new Regex(@"{(?w+)}", RegexOptions.Compiled); public static string Expand(this string src, Dictionary vals) => varPattern.Replace(src, m => vals.TryGetValue(m.Groups[1].Value, out var v) ? v : m.Value); } 

以下是使用它的示例代码:

 var ans = templates.ToDictionary(kv => kv.Key, kv => kv.Value.Expand(values)); 

超过10,000个重复扩展,其values 18个条目,通常只有一个替换,比多个String.Replace调用快3倍。

不,这是不可能的,相反,你应该使用String.Format 。

使用String格式,您的字符串模板看起来像string template = "The temperature is {0}°C." 然后插入你可以的值:

 decimal temp = 20.4m; string s = String.Format(template, temp); 

如Microsoft示例中所示。

我认为正则表达式的最佳替代方法是对每个可能的值键执行Replace ,但速度更快取决于您拥有的值以及这些值的常见替换值。

 var templates = new Dictionary { { "Key1", "{Value1}" }, { "Key2", "Constant with {Value2}" } }; var values = new Dictionary { { "Value1", "1" }, { "Value2", "example 2" } }; var ans = templates.ToDictionary(kv => kv.Key, kv => values.Aggregate(kv.Value, (s, v) => s.Replace($"{{{v.Key}}}", v.Value))); 

请注意, foreach而不是Aggregate会稍微快一些,这取决于values条目数。 此外,预先构建新的键和值,其中键已经被大括号包围,可以带来4倍的加速,但我们在谈论您的示例中的毫秒数。

 var subkeys = values.Select(kv => $"{{{kv.Key}}}").ToArray(); var subvals = values.Select(kv => kv.Value).ToArray(); var ans4 = templates.ToDictionary(kv => kv.Key, kv => { var final = kv.Value; for (int j1 = 0; j1 < subkeys.Length; ++j1) final = final.Replace(subkeys[j1], subvals[j1]); return final; }); 

当然,如果你的values数组随着每个方法调用而改变,那么使用两个带有围绕键的大括号的List将是一个更好的存储结构,因为每次翻译都会节省时间。

上述就是C#学习教程:延迟模板字符串插值分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注---计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/991526.html

(0)
上一篇 2021年12月23日
下一篇 2021年12月23日

精彩推荐