不,但这种扩展方法会做到这一点
static string FormatFromDictionary(this string formatString, DictionaryValueDict) { int i = 0; StringBuilder newFormatString = new StringBuilder(formatString); Dictionary keyToInt = new Dictionary (); foreach (var tuple in ValueDict) { newFormatString = newFormatString.Replace("{" + tuple.Key + "}", "{" + i.ToString() + "}"); keyToInt.Add(tuple.Key, i); i++; } return String.Format(newFormatString.ToString(), ValueDict.OrderBy(x => keyToInt[x.Key]).Select(x => x.Value).ToArray()); }
检查一下,它支持格式化:
public static string StringFormat(string format, IDictionaryvalues) { var matches = Regex.Matches(format, @"\{(.+?)\}"); List words = (from Match matche in matches select matche.Groups[1].Value).ToList(); return words.Aggregate( format, (current, key) => { int colonIndex = key.IndexOf(':'); return current.Replace( "{" + key + "}", colonIndex > 0 ? string.Format("{0:" + key.Substring(colonIndex + 1) + "}", values[key.Substring(0, colonIndex)]) : values[key].ToString()); }); }
如何使用:
string format = "{foo} is a {bar} is a {baz} is a {qux:#.#} is a really big {fizzle}"; var dictionary = new Dictionary{ { "foo", 123 }, { "bar", true }, { "baz", "this is a test" }, { "qux", 123.45 }, { "fizzle", DateTime.Now } }; StringFormat(format, dictionary)
使用C#6.0的Interpolated Strings,您可以这样做:
string name = "John"; string message = $"Hi {name}!"; //"Hi John!"