Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
343 views
in Technique[技术] by (71.8m points)

c# - C#6.0 string interpolation localization

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

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

The example is converted to

 var name = "John";
 WriteLine(String.Format("My name is {0}", name));

From the localization point of view, it is much better to store strings like :

"My name is {name} {middlename} {surname}" 

than in String.Format notation:

"My name is {0} {1} {2}"

How to use the string interpolation for .NET localization? Is there going to be a way to put $"..." to resource files? Or should strings be stored like "...{name}" and somehow interpolated on fly?

P.S. This question is NOT about "how to make string.FormatIt extension" (there are A LOT of such libraries, SO answers, etc.). This question is about something like Roslyn extension for "string interpolation" in "localization" context (both are terms in MS .NET vocabulary), or dynamic usage like Dylan proposed.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...