C#6.0 string interpolation localization

前端 未结 9 1244
感情败类
感情败类 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:30

    String interpolation is difficult to combine with localization because the compiler prefers to translate it to string.Format(...), which does not support localization. However, there is a trick that makes it possible to combine localization and string interpolation; it is described near the end of this article.

    Normally string interpolation is translated to string.Format, whose behavior cannot be customized. However, in much the same way as lambda methods sometimes become expression trees, the compiler will switch from string.Format to FormattableStringFactory.Create (a .NET 4.6 method) if the target method accepts a System.FormattableString object.

    The problem is, the compiler prefers to call string.Format if possible, so if there were an overload of Localized() that accepted FormattableString, it would not work with string interpolation because the C# compiler would simply ignore it [because there is an overload that accepts a plain string]. Actually, it's worse than that: the compiler also refuses to use FormattableString when calling an extension method.

    It can work if you use a non-extension method. For example:

    static class Loca
    {
        public static string lize(this FormattableString message)
            { return message.Format.Localized(message.GetArguments()); }
    }
    

    Then you can use it like this:

    public class Program
    {
        public static void Main(string[] args)
        {
            Localize.UseResourceManager(Resources.ResourceManager);
    
            var name = "Dave";
            Console.WriteLine(Loca.lize($"Hello, {name}"));
        }
    }
    

    It's important to realize that the compiler converts the $"..." string into an old-fashioned format string. So in this example, Loca.lize actually receives "Hello, {0}" as the format string, not "Hello, {name}".

提交回复
热议问题