作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
CurrentCulture
有什么区别, InvariantCulture
, CurrentUICulture
和 InstalledUICulture
来自 System.Globalization.CultureInfo
?
最佳答案
我会尝试给出比 this one 更有见地的答案。
CurrentCulture 应该用于格式化。也就是说,数字、货币、百分比、日期和时间在向用户显示之前应始终使用这种文化进行格式化。这里的几个例子:
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
是正确的选择)。
CurrentCulture
的另一个常见用例是 Locale-aware 解析。您的应用程序应始终允许用户以其区域格式提供输入:
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 将忽略此参数视为错误的原因之一。
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
Version
类需要文化不变的输入。
CurrentUICulture
是不错的选择(前提是您实际上是从 Web 浏览器读取此属性的)。
CurrentUICulture
。
This property is the equivalent of GetSystemDefaultUILanguage in the Windows API.
关于.net - CurrentCulture、InvariantCulture、CurrentUICulture 和 InstalledUICulture 之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5060446/
CurrentCulture有什么区别, InvariantCulture , CurrentUICulture和 InstalledUICulture来自 System.Globalization.
我是一名优秀的程序员,十分优秀!