带有变量字符串和参数数量的.NET String.Format

时间:2018-05-04 11:33:04

标签: .net string format

我想创建一个接受字符串MyString和字符串MyList的方法。

MyString包含{0},{1}等占位符......但我事先并不知道有多少个占位符。示例:"我想在此处添加一些内容:{0}以及其他内容:{1}"

MyList包含必须在MyString中替换的字符串,在正确的位置:第一个字符串,索引为0,必须放在占位符{0}中。

我想用String.Format实现这个目的,但我不能理解如何将MyString作为参数列表传递。

这在VB.NET中是否可行?

谢谢

1 个答案:

答案 0 :(得分:1)

只需将您的列表转换为数组,然后即可调用this overload

string result = string.Format(formatString, list.ToArray());

例如:

string formatString = "I want to put something here: {0} and something there: {1}";
var list = new List<string> { "foo", "bah" };
string result = string.Format(formatString, list.ToArray());
// Result:  I want to put something here: foo and something there: bah

如果您通过了列表,则会使用wrong overload of String.Format

对不起C#,这里是VB.NET:

Dim result = String.Format(formatString, list.ToArray())