What is the default culture for C# 6 string interpolation?

丶灬走出姿态 提交于 2019-11-29 15:56:33

问题


In C# 6 what is the default culture for the new string interpolation?

I've seen conflicting reports of both Invariant and Current Culture.

I would like a definitive answer and I'm keeping my fingers crossed for Invariant.


回答1:


Using string interpolation in C# is compiled into a simple call to String.Format. You can see with TryRolsyn that this:

public void M()
{
    string name = "bar";
    string result = $"{name}";
}

Is compiled into this:

public void M()
{
    string arg = "bar";
    string text = string.Format("{0}", arg);
}

It's clear that this doesn't use an overload that accepts a format provider, hence it uses the current culture.

You can however compile the interpolation into FormattbleString instead which keeps the format and arguments separate and pass a specific culture when generating the final string:

FormattableString formattableString = $"{name}";
string result = formattableString.ToString(CultureInfo.InvariantCulture);

Now since (as you prefer) it's very common to use InvariantCulture specifically there's a shorthand for that:

string result = FormattableString.Invariant($"{name}");


来源:https://stackoverflow.com/questions/33203261/what-is-the-default-culture-for-c-sharp-6-string-interpolation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!