C#6字符串插值的默认区域性是什么?

编程入门 行业动态 更新时间:2024-10-22 22:52:31
本文介绍了C#6字符串插值的默认区域性是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在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字符串插值的默认区域性是什么?

本文发布于:2023-11-08 14:05:20,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1569583.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:区域性   字符串   插值

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!