我认为你能够接近的最好方式是使用索引格式:
String.Format("{0} has {1} quote types.", "C
如果你愿意分多步进行,并相信你不会在字符串的其他地方找到“变量”,那么还有String.Replace()可用:
string MyString = "{language} has {n} quote types.";
MyString = MyString.Replace("{language}", "C#").Replace("{n}", "1");
将其扩展为使用列表:
List<KeyValuePair<string, string>> replacements = GetFormatDictionary();
foreach (KeyValuePair<string, string> item in replacements)
{
MyString = MyString.Replace(item.Key, item.Value);
}
您也可以使用Dictionary<string, string>,通过遍历其.Keys集合来实现此操作,但是通过使用List<KeyValuePair<string, string>>,我们可以利用List的.ForEach()方法并将其压缩为一行:
replacements.ForEach(delegate(KeyValuePair<string,string>) item) { MyString = MyString.Replace(item.Key, item.Value)
一个lambda表达式可能更简单,但我还在使用.Net 2.0。另外需要注意的是,当迭代使用.Replace()时,性能并不出色,因为在.Net中字符串是不可变的。此外,这需要以某种方式定义
MyString
变量,使其可以被委托访问,所以它还不完美。