31 c# string.format
而不是使用{0} {1},等我想要使用{title}.然后以某种方式填充该数据(下面我使用了a Dictionary).此代码无效并引发异常.我想知道我是否能做类似于我想要的事情.使用{0 .. N}不是问题.我只是好奇而已.
Dictionary<string, string> d = new Dictionary<string, string>();
d["a"] = "he";
d["ba"] = "llo";
d["lol"] = "world";
string a = string.Format("{a}{ba}{lol}", d);
Run Code Online (Sandbox Code Playgroud)
LPC*_*Roy 15
不,但这种扩展方法会做到这一点
static string FormatFromDictionary(this string formatString, Dictionary<string, string> ValueDict)
{
int i = 0;
StringBuilder newFormatString = new StringBuilder(formatString);
Dictionary<string, int> keyToInt = new Dictionary<string,int>();
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());
}
Run Code Online (Sandbox Code Playgroud)
检查一下,它支持格式化:
public static string StringFormat(string format, IDictionary<string, object> values)
{
var matches = Regex.Matches(format, @"\{(.+?)\}");
List<string> 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());
});
}
Run Code Online (Sandbox Code Playgroud)
如何使用:
string format = "{foo} is a {bar} is a {baz} is a {qux:#.#} is a really big {fizzle}";
var dictionary = new Dictionary<string, object>
{
{ "foo", 123 },
{ "bar", true },
{ "baz", "this is a test" },
{ "qux", 123.45 },
{ "fizzle", DateTime.Now }
};
StringFormat(format, dictionary)
Run Code Online (Sandbox Code Playgroud)
您可以实现自己的:
public static string StringFormat(string format, IDictionary<string, string> values)
{
foreach(var p in values)
format = format.Replace("{" + p.Key + "}", p.Value);
return format;
}
Run Code Online (Sandbox Code Playgroud)
使用C#6.0的Interpolated Strings,您可以这样做:
string name = "John";
string message = $"Hi {name}!";
//"Hi John!"
Run Code Online (Sandbox Code Playgroud)