名为String.Format,有可能吗?

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)

  • 小心,在`formatString`中使用"{{thing}}"并在`ValueDict`中使用名为"thing"的键将替换字符串中的"thing"作为数字. (5认同)

Pav*_*man 7

检查一下,它支持格式化:

    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)


eul*_*rfx 5

您可以实现自己的:

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)

  • 但这失去了 String.Format 的很多功能。 (6认同)

fab*_*tto 5

现在可能了

使用C#6.0的Interpolated Strings,您可以这样做:

string name = "John";
string message = $"Hi {name}!";
//"Hi John!"
Run Code Online (Sandbox Code Playgroud)

  • 这不是要求的.如果您不知道该字段的调用内容,则不能为该标识符准备好变量. (5认同)

mic*_*tan -3

(你的 Dictionary + foreach + string.Replace)包裹在子例程或扩展方法中?

显然没有优化,但是......