C#6.0 string interpolation localization

前端 未结 9 1247
感情败类
感情败类 2020-11-29 04:59

C#6.0 have a string interpolation - a nice feature to format strings like:

 var name = \"John\";
 WriteLine($\"My name is {name}\");

The ex

9条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-29 05:28

    As already said in previous answers: you currently cannot load the format string at runtime (e.g. from resource files) for string interpolation because it is used at compile time.

    If you don't care about the compile time feature and just want to have named placeholders, you could use something like this extension method:

    public static string StringFormat(this string input, Dictionary elements)
    {
        int i = 0;
        var values = new object[elements.Count];
        foreach (var elem in elements)
        {
            input = Regex.Replace(input, "{" + Regex.Escape(elem.Key) + "(?[^}]+)?}", "{" + i + "${format}}");
            values[i++] = elem.Value;
        }
        return string.Format(input, values);
    }
    

    Be aware that you cannot have inline expressions like {i+1} here and that this is not code with best performance.

    You can use this with a dictionary you load from resource files or inline like this:

    var txt = "Hello {name} on {day:yyyy-MM-dd}!".StringFormat(new Dictionary
                {
                    ["name"] = "Joe",
                    ["day"] = DateTime.Now,
                });
    

提交回复
热议问题