什么是不变的文化?文化

2023-09-02 01:24:41 作者:相关繁体字长>>

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

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);