C#6.0 string interpolation localization

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

    Using the Microsoft.CodeAnalysis.CSharp.Scripting package you can achieve this.

    You will need to create an object to store the data in, below a dynamic object is used. You could also create an specific class with all the properties required. The reason to wrap the dynamic object in a class in described here.

    public class DynamicData
    {
        public dynamic Data { get; } = new ExpandoObject();
    }
    

    You can then use it as shown below.

    var options = ScriptOptions.Default
        .AddReferences(
            typeof(Microsoft.CSharp.RuntimeBinder.RuntimeBinderException).GetTypeInfo().Assembly,
            typeof(System.Runtime.CompilerServices.DynamicAttribute).GetTypeInfo().Assembly);
    
    var globals = new DynamicData();
    globals.Data.Name = "John";
    globals.Data.MiddleName = "James";
    globals.Data.Surname = "Jamison";
    
    var text = "My name is {Data.Name} {Data.MiddleName} {Data.Surname}";
    var result = await CSharpScript.EvaluateAsync($"$\"{text}\"", options, globals);
    

    This is compiling the snippet of code and executing it, so it is true C# string interpolation. Though you will have to take into account the performance of this as it is actually compiling and executing your code at runtime. To get around this performance hit if you could use CSharpScript.Create to compile and cache the code.

提交回复
热议问题