我在英语Windows 7上使用英语Visual Studio 2008,但我的总部设在荷兰。我的很多程序都需要读写浮点数。与英语相比,荷兰数字符号改变了点和逗号的含义(即荷兰语中的1.001是千分之一,1,001是1 + 1/1000)。我永远不会用荷兰语编写(或读取)数字,但由于某种原因,我编译的每个程序都默认为它,因此每个ToString()都是错误的。每次都让我受益匪浅。我知道我可以把它放在每个线程的开头:
System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture("en-US");
或者用:
替换ToString()的每个实例String.Format(CultureInfo.InvariantCulture, "{0:0.####},{1:0.####}", x)
但有时我只是想编译一些东西,看它是如何工作的,而不是做任何改变。而且,我有时会忘记这一点。有没有办法告诉C#,.NET和/或Visual Studio总是让我的所有项目/程序都使用英文数字格式?
答案 0 :(得分:5)
这不是编译的问题 - 这是执行时间发生的事情。除非您明确指定文化,否则将使用当前文化(在执行时)。没有办法改变我所知道的这种行为,这使你可以选择:
请注意,即使您更改当前线程的当前文化,也可能不会影响线程池之类的内容。我个人认为最好总是明确地使用这种文化。
您总是可以编写自己的扩展方法(比如说)调用原始版本,但是传入CultureInfo.InvariantCulture。例如:
public static string ToInvariantString(this IFormattable source, string format)
{
return source.Format(format, CultureInfo.InvariantCulture);
}
正确地无处不在可能是一种痛苦,诚然......并且为了避免拳击,你实际上想要一个稍微不同的签名:
public static string ToInvariantString<T>(this T source, string format)
where T : IFormattable
{
return source.Format(format, CultureInfo.InvariantCulture);
}
答案 1 :(得分:1)
您可以在项目模板中添加一行,将CurrentCulture
设置为Program.cs
。
答案 2 :(得分:-1)
尝试:Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;