名为String.Format,可以吗? [英] named String.Format, is it possible?
本文介绍了名为String.Format,可以吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
而不是使用 {0} {1}
等。我想使用 {title}
。然后以某种方式填充该数据(下面我使用了 Dictionary
)。此代码无效,并引发异常。我想知道我是否可以做类似于我想要的事情。使用 {0 .. N}
没问题。我只是好奇。
Instead of using {0} {1}
, etc. I want to use {title}
instead. Then fill that data in somehow (below I used a Dictionary
). This code is invalid and throws an exception. I wanted to know if i can do something similar to what i want. Using {0 .. N}
is not a problem. I was just curious.
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);
推荐答案
否,但是此扩展方法可以做到
No, but this extension method will do it
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());
}
这篇关于名为String.Format,可以吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文