在C#6中,新字符串插值的默认区域性是什么?
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.
推荐答案在C#中使用字符串插值被编译为对 String.Format 的简单调用.你可以用 TryRolsyn 看到这一点:
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}"; }已被编译为:
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.
不过,您可以将插值编译为 FormattbleString ,这样可以将格式和参数分开,并在生成最终字符串时传递特定的区域性:
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);现在,由于(如您所愿),使用 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}");更多推荐
C#6字符串插值的默认区域性是什么?
发布评论