命名的String.Format,这可能吗? C# [英] named String.Format, is it possible? C#
本文介绍了命名的String.Format,这可能吗? C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
而不是使用{0} {1},等我想用{}标题代替。然后填写莫名其妙的数据(下面我用一个字典)。这code是无效的,并抛出一个异常。我想知道如果我可以做类似我想要什么东西。使用{0 ... N}是没有问题的。我只是好奇。
词典<字符串,字符串> D =新词典<字符串,字符串>();
D [一] =他;
D [BA] =LLO;
D [笑] =世界;
字符串=的String.Format({一} {巴} {}笑,D);
解决方案
没有,但这种扩展方法将做到这一点。
静态字符串FormatFromDictionary(这个字符串的formatString,字典<字符串,字符串> ValueDict)
{
INT I = 0;
StringBuilder的newFormatString =新的StringBuilder(formatString中);
字典<字符串,整数> keyToInt =新词典<字符串,整数>();
的foreach(在ValueDict VAR元组)
{
newFormatString = newFormatString.Replace({+ tuple.Key +},{+ i.ToString()+});
keyToInt.Add(tuple.Key,I);
我++;
}
返回的String.Format(newFormatString.ToString(),ValueDict.OrderBy(X => keyToInt [x.Key])选择(X =方式> x.Value).ToArray());
}
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,这可能吗? C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文