【问题标题】:How to make C# write English (non-localized) number format by default?如何让C#默认写英文(非本地化)数字格式?
【发布时间】:2011-04-30 05:50:32
【问题描述】:

我在英语 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 总是让我的所有项目/程序使用英文数字格式?

【问题讨论】:

  • 写ToString(CultureInfo.InvariantCulture)有什么问题?
  • 不简洁(也不能和"examplestr"+1.0一起使用,自动字符串转换),我偶尔会忘记,其他人已经忘记在我将使用的代码中使用了.

标签: c# visual-studio-2008 localization number-formatting


【解决方案1】:

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

  • 明确说明要使用的文化
  • 显式更改当前文化

请注意,即使您更改了 current 线程的当前文化,也可能不会影响线程池之类的东西。就我个人而言,我认为始终明确地使用文化会更好。

您始终可以编写自己的扩展方法来(例如)调用原始版本,但传入 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);
}

【讨论】:

  • 应该不是扩展方法static?
  • @Desolator:是的,抱歉 - 现已修复。
【解决方案2】:

您可以在项目模板中添加将CurrentCulture 设置为Program.cs 的行。

【讨论】:

    【解决方案3】:

    试试:Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;

    【讨论】:

    • 如果windows格式不是英文数字,​​这将不起作用
    猜你喜欢
    • 2018-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多