假设我的数据库中存储了一个元数据资源字符串,它将像这样返回:
var pageTitle = "Shop the latest {category1} Designer {category2} {category3} at www.abc.com";
我想用变量 values
替换 {placeholders}
;
var category1 = "womenswear";
var category2 = "dresses";
var category3 = "cocktail dresses";
我试过了,没有运气;
var newTitle = $"pageTitle, category1, category2, category3";
var newTitle = $(pageTitle, category1, category2, category3);
我知道我可以使用具有性能开销的 string.Replace()
。有谁知道如何使用最新的 C# 字符串插值有效地完成此操作?
最佳答案
你不能在这里使用字符串插值。字符串插值是string.Format
的编译时重写方法,这是你应该使用的解决方案:
var newTitle = string.Format("{0}, {1}, {2}, {3}", pageTitle, category1, category2, category3);
或者string.Join
:
var newTitle - string.Join(", ", new string[] { pageTitle, category1, category2, category3 });
由于您是从数据库加载的,因此在您的情况下继续使用 string.Replace
可能会更好。
关于c# - 在 C#6 中使用命名参数进行字符串插值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36745164/