And*_*zub 123
不变文化是一种特殊的文化,它是有用的,因为它不会改变.当前的文化可以从一个用户变为另一个用户,甚至从一个用户变为另一个用户,因此您不能依赖它保持不变.
能够每次使用相同的文化在几个流程中非常重要,例如,序列化:您可以在一种文化中具有1,1值,在另一种文化中具有1.1值.如果您将尝试在第二种文化中解析"1,1"值,则解析将失败.但是,您可以使用不变文化将数字转换为字符串,然后从具有任何文化集的任何计算机中将其解析回来.
// 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);
Run Code Online (Sandbox Code Playgroud)
小智 108
基于英语和定义行为的虚假文化.很高兴将内容写入配置文件,以便无论用户定义的文化如何都可以读取和写入.
基本上它是一种特定的文化,是人为的,不会改变.
无论文化如何,它都用于相同的东西(不需要翻译成某种文化X是合适的)
例如 - https://msdn.microsoft.com/en-us/library/4c5zdc6a(v=vs.100).aspx.当您编写用户不应该使用的特定于应用程序的文件时,您应该将InvariantCulture用于接受culture参数的所有方法.
请注意,根据上面链接的文档:
但是,应用程序应仅对需要与文化无关的结果的进程使用不变文化,例如格式化和解析持久保存到文件的数据.