如何使C#默认编写英文(非本地化)数字格式?

Jor*_*rdi 1 c# localization visual-studio-2008 number-formatting

我在英语Windows 7上使用英语Visual Studio 2008,但我的总部设在荷兰.我的很多程序都需要读写浮点数.与英语相比,荷兰数字符号改变了点和逗号的含义(即荷兰语中的1.001是千分之一,而1,001是1 + 1/1000).我永远不会用荷兰语编写(或读取)数字,但由于某种原因,我编译的每个程序都默认为它,因此每个ToString()都是错误的.这让我每次都这样.我知道我可以把它放在每个线程的开头:

System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture("en-US");
Run Code Online (Sandbox Code Playgroud)

或者用以下内容替换ToString()的每个实例:

String.Format(CultureInfo.InvariantCulture, "{0:0.####},{1:0.####}", x)
Run Code Online (Sandbox Code Playgroud)

但有时我只是想编译一些东西来看看它是如何工作的,而不是做任何改变.而且,我有时会忘记这一点.有没有办法告诉C#,.NET和/或Visual Studio总是让我的所有项目/程序都使用英文数字格式?

Jon*_*eet 5

这不是编译的问题 - 这是执行时发生的事情.除非您明确指定文化,否则将使用当前文化(在执行时).没有办法改变我所知道的这种行为,这使你可以选择:

  • 明确说明要使用的文化
  • 明确改变当前的文化

请注意,即使您更改当前线程的当前区域性,也可能不会影响线程池之类的内容.就个人而言,我认为最好总是明确地使用文化.

您总是可以编写自己的扩展方法(比如说)调用原始版本,但是传入CultureInfo.InvariantCulture.例如:

public static string ToInvariantString(this IFormattable source, string format)
{
    return source.Format(format, CultureInfo.InvariantCulture);
}
Run Code Online (Sandbox Code Playgroud)

无论如何,在各地都能做到这一点可能是一种痛苦......并且为了避免拳击,你实际上想要一个稍微不同的签名:

public static string ToInvariantString<T>(this T source, string format)
    where T : IFormattable
{
    return source.Format(format, CultureInfo.InvariantCulture);
}
Run Code Online (Sandbox Code Playgroud)