c# - 带有前导零的 int.Parse()

标签 c# .net

如何防止下面的代码抛出 FormatException。我希望能够将带有前导零的字符串解析为整数。有没有一种干净的方法可以做到这一点?

string value = "01";
int i = int.Parse(value);

最佳答案

您的代码为我运行,没有 FormatException(一旦您正确地使用了该方法):

string value = "01";
int i = int.Parse(value);

但这确实敲响了警钟;这是我多年前遇到的一个问题,Microsoft 将其视为针对 Windows(而非 .NET)本地化组件的错误。要测试您是否看到了这一点,请运行此代码并让我们知道您是否收到 FormatException:

string value = "0"; // just a zero
int i = int.Parse(value);

编辑:这是我 2007 年在 Usenet 上发的帖子。看看症状是否与您的相符。

For reference, here's what we found. The affected machine had bad data for the registry value [HKEY_CURRENT_USER\Control Panel \International\sPositiveSign]. Normally, this value is an empty REG_SZ (null-terminated string). In this case, the string was missing its terminator. This confused the API function GetLocaleInfoW(), causing it to think that '0' (ASCII number zero) was the positive sign for the current locale (it should normally be '+'). This caused all kinds of havoc.

You can verify this for yourself with regedit.exe: open that reg value by right-clicking on the value and selecting 'Modify Binary Data'. You should see two dots on the right (representing the null terminator). If you see no dots, you're affected. Fix it by adding a terminator (four zeros).

You can also check the value of CultureInfo.CurrentCulture.NumberFormat.PositiveSign; it should be '+'.

It's a bug in the Windows localization API, not the class libs. The reg value needs to be checked for a terminator. They're looking at it.

...和here's a report on Microsoft Connect关于这个问题:

关于c# - 带有前导零的 int.Parse(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1677516/

相关文章:

c# - 您将如何重构此条件以使用多态性?

c# - 如果适用,将嵌套的 ForEach 替换为 Select

.net - 通过 .Net 设置 Windows 进程 'Comment'?

c# - 从 TextBlock MouseDown 获取 DataContext

不使用 GetHashCode 的 HashSet 和 Dictionary 的 C# 高性能替代品

c# - 如何从 X509Certificate2 获取组织名称?

.net - 是否可以通过编程方式升级/降级到正在运行的ClickOnce应用程序的特定版本?

c# - 将记录器作为单例是一种好习惯吗?

c# - EasyHook,.NET Remoting 在客户端和服务器之间共享接口(interface)?

c# - 在 Visual Studio 中调试时,某些对象显示为 System.__ComObject