Skip to main content
 首页 » 编程设计

c#之如何使用带有可变参数的 string.Format() 替换占位符

2024年02月13日33mq0036

我有这样的文字:This is my {0} body from {1} configuration file {2}!

我的参数存储在 List<string> 中称为 TextArguments .

现在,如果我编码:this.Text = string.Format(this.Text, this.TextArguments.ToArray<string>())它工作正常。

但如果我尝试使用建议的扩展方法 FormatWith(例如 this.Text.FormatWith(this.TextArguments.ToArray<string>()),占位符不会被替换。

有什么想法吗?

PS:这里推荐的扩展方法:Replacing multiple placeholders in a string

请您参考如下方法:

字符串是不可变的,因此您需要重新分配结果:

this.Text = this.Text.FormatWith(this.TextArguments.ToArray<string>())