什么是不变的文化? [英] What is the Invariant Culture?

查看:137
本文介绍了什么是不变的文化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人可以举一个例子来证明不变文化的使用情况如何?我不明白(我已阅读)哪些文档描述。

Could anybody give an example to demonstrate the usage of Invariant Culture? I don't understand (I have read) what the documentation describes.

推荐答案

不变的文化是一种特殊的文化,你总是可以在任何.NET应用程序中使用。这是在几个流量非常有用,例如序列化:你可以在一种文化中另一个1.1 1,1价值。如果你尝试将其解析1,1的价值与文化。小数点符号,然后解析会失败。但是,您可以使用不变的文化数字转换为字符串并解析它回来 - 这肯定会与任何文化集中的任何计算机上正常工作

Invariant culture is a special culture that you can always use in any .NET application. It is very useful in several flows, for example serialization: you can have 1,1 value in one culture and 1.1 in another. If you will try to parse "1,1" value in the culture with "." decimal symbol then parsing will fail. However you can use Invariant culture to convert number to string and parse it back - this will definitely work on any computer with any culture set.

// Use some non invariant culture.
CultureInfo nonInvariantCulture = new CultureInfo("en-US");
Thread.CurrentThread.CurrentCulture = nonInvariantCulture;

decimal dec = 1.1m;
string convertedToString = dec.ToString();

// Simulate another culture being used,
// following code can run on another computer.
nonInvariantCulture.NumberFormat.NumberDecimalSeparator = ",";

decimal parsedDec;

try
{
    // This fails because value cannot be parsed.
    parsedDec = decimal.Parse(convertedToString);
}
catch (FormatException)
{
}

// However you always can use Invariant culture:
convertedToString = dec.ToString(CultureInfo.InvariantCulture);

// This will always work because you serialized with the same culture.
parsedDec = decimal.Parse(convertedToString, CultureInfo.InvariantCulture);

这篇关于什么是不变的文化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆