CurrentCulture
、InvariantCulture
、CurrentUICulture
和InstalledUICulture
与System.Globalization.CultureInfo
有什么区别?
CurrentCulture
、InvariantCulture
、CurrentUICulture
和InstalledUICulture
与System.Globalization.CultureInfo
有什么区别?
我会试着给出比this one更有洞察力的答案.
CurrentCulture应该用于格式化.也就是说,数字、货币、百分比、日期和时间always应该在displaying them to user之前使用这种文化进行格式化.这里没有几个例子:
const string CURRENCY_FORMAT = "c";
const string PERCENTAGE_FORMAT = "p";
DateTime now = DateTime.UtcNow; // all dates should be kept in UTC internally
// convert time to local and format appropriately for end user
dateLabel.Text = now.ToLocalTime().ToString(CultureInfo.CurrentCulture);
float someFloat = 12.3456f;
// yields 12,3456 for pl-PL Culture
floatLabel.Text = someFloat.ToString(CultureInfo.CurrentCulture);
// yields 12,35 zł for pl-PL Culture - rounding takes place!
currencyLabel.Text = someFloat.ToString(CURRENCY_FORMAT, CultureInfo.CurrentCulture);
// yields 1234,56% for pl-PL Culture - 1.0f is 100%
percentageLabel.Text = someFloat.ToString(PERCENTAGE_FORMAT, CultureInfo.CurrentCulture);
需要注意的一件重要事情是,你不应该首先使用float
或double
来存储货币相关的信息(decimal
是正确的 Select )
float parsedFloat;
if (float.TryParse(inputBox.Text, NumberStyles.Float, CultureInfo.CurrentCulture, out parsedFloat))
{
MessageBox.Show(parsedFloat.ToString(CultureInfo.CurrentCulture), "Success at last!");
}
请注意,我总是提供IFormatProvider
个参数,尽管它是隐含的,并假定为CultureInfo.CurrentCulture
.原因是,我想与其他开发人员交流:这是将向最终用户显示的内容.这就是FxCop将忽略此参数视为错误的原因之一.
另一方面,InvariantCulture应该用于可靠地将上述类之一转换为其文本表示.因此,例如,如果您希望通过网络传输DateTime
、float
、double
或类似对象,将其存储到数据库或某种文本文件(包括XML)中,您应该使用InvariantCulture
:
float someFloat = 1234.56f;
// yields 1234.56
string internalFloat = someFloat.ToString(CultureInfo.InvariantCulture);
DateTime now = DateTime.UtcNow;
// yields something like 04/16/2011 19:02:46
string internalDateAndTime = now.ToString(CultureInfo.InvariantCulture);
这里需要注意的是,InvariantCulture
提供的日期/时间格式实际上与en US完全相同.虽然它是可靠的,但并不完全正确.真正应该使用的是ISO8601 Interchangeable Date & Time Format.出于某种原因,微软甚至没有提供这样的模式(最接近的是可排序模式——"s"和通用模式——"u",它只类似于ISO8601格式),您需要创建自己的模式,如下所示:
const string iso8601Pattern = "yyyy-MM-dd'T'HH:mm:ss'Z'";
string iso8601Formatted = now.ToString(iso8601Pattern);
非常重要的补充说明:这里IFormatProvider
实际上是required,因为省略这个参数可能会导致严重错误.我曾经不得不修复法语操作系统的一个缺陷.代码是这样的:
float dbVersion = // some kind of logic that took float from database string versionString = dbVersion.ToString(); // culture-aware formatting used Version ver = new Version(versionString); // exception thrown here
原因很简单:在法语操作系统上格式化的float(使用法语区域格式)被格式化为10、5和Version
,类需要区域性不变的输入.
CurrentUICulture负责为您的应用程序加载适当的可翻译资源.也就是说,它应该用于显示正确的文本消息、 colored颜色 和图像
InstalledUICulture连接到默认的OS UI区域设置.正如MSDN说的那样:
此属性相当于Windows API中的GetSystemDefaultUILanguage.
要真正理解这个属性是什么,我们需要深入研究一些理论.有不同的Windows产品线:
对于单语言产品线,InstalledCulture将始终返回操作系统语言,而对于MUI,它应始终返回英语(美国)又名en US.它有用吗?我不知道,我从来都不需要这样的信息.就我个人而言,我还没有见过利用这一优势的项目.