C#6.0 string interpolation localization

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

    An interpolated string evaluates the block between the curly braces as a C# expression (e.g. {expression}, {1 + 1}, {person.FirstName}).

    This means that the expressions in an interpolated string must reference names in the current context.

    For example this statement will not compile:

    var nameFormat = $"My name is {name}"; // Cannot use *name*
                                           // before it is declared
    var name = "Fred";
    WriteLine(nameFormat);
    

    Similarly:

    class Program
    {
        const string interpolated = $"{firstName}"; // Name *firstName* does not exist
                                                    // in the current context
        static void Main(string[] args)
        {
            var firstName = "fred";
            Console.WriteLine(interpolated);
            Console.ReadKey();
        }
    }
    

    To answer your question:

    There is no current mechanism provided by the framework to evaluate interpolated strings at runtime. Therefore, you cannot store strings and interpolate on the fly out of the box.

    There are libraries that exist that handle runtime interpolation of strings.

提交回复
热议问题