C# 将字符串“0”解析为整数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/691199/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 13:39:41  来源:igfitidea点击:

C# parse string "0" to integer

c#

提问by Les

I have a new laptop at work and code that worked earlier in the week does not work today.

我有一台新的笔记本电脑在工作,本周早些时候工作的代码今天不起作用。

The code that worked before is, simplified:

以前工作的代码简化了:

while (dr.Read())
{
    int i = int.Parse(dr.GetString(1))
}

Now it fails when the database value is 0. Sometimes, but not reliably, this will work instead:

现在,当数据库值为 0 时它会失败。有时,但不可靠,这会起作用:

while (dr.Read())
{
    int i = Convert.ToInt32(dr["FieldName"]))
}

Am I missing something stupid?

我错过了一些愚蠢的东西吗?

Oddly enough, ReSharper is also having tons of weird errors with the same error message that I am getting with the above code: "input string was not in the correct format." (Starts before I even load a project.)

奇怪的是,ReSharper 也有大量奇怪的错误,错误消息与我在上面的代码中得到的错误消息相同:“输入字符串的格式不正确。” (在我什至加载项目之前开始。)

Any ideas? Anyone having any SP issues? I did try to make sure all my SPs were up-to-date when I got the machine.

有任何想法吗?有人有任何SP问题吗?当我拿到机器时,我确实尝试确保我所有的 SP 都是最新的。

EDIT: I understand how to use Try.Parse and error-handling. The code here is simplified. I am reading test cases from a database table. This column has only 0, 1, and 2 values. I have confirmed that. I broke this down putting the database field into a string variable s and then trying int.Parse(s). The code worked earlier this week and the database has not changed. The only thing that has changed is my environment.

编辑:我了解如何使用 Try.Parse 和错误处理。这里的代码被简化了。我正在从数据库表中读取测试用例。此列只有 0、1 和 2 个值。我已经证实了这一点。我打破了这一点,将数据库字段放入字符串变量 s 中,然后尝试 int.Parse(s)。代码在本周早些时候工作,数据库没有改变。唯一改变的是我的环境。

To completely simplify the problem, this line of code throws an exception ("input string was not in the correct format"):

为了完全简化问题,这行代码抛出一个异常(“输入字符串的格式不正确”):

 int.Parse("0");

EDIT: Thanks to everyone for helping me resolve this issue! The solution was forcing a reset of my language settings.

编辑:感谢大家帮助我解决这个问题!解决方案是强制重置我的语言设置。

采纳答案by John Rasch

A possible explanation:

一个可能的解释

Basically, the problem was the sPositiveSign value under HKEY_CURRENT_USER\Control Panel\International being set to 0, which means the positive sign is '0'. Thus, while parsing the "positive sign 0" is being cut off and then the rest of the string ("") is parsed as a number, which doesn't work of course. This also explains why int.Parse("00") wasn't a problem. Although you can't set the positive sign to '0' through the Control Panel, it's still possible to do it through the registry, causing problems. No idea how the computer of the user in the post ended up with this wrong setting...

基本上,问题是 HKEY_CURRENT_USER\Control Panel\International 下的 sPositiveSign 值被设置为 0,这意味着正号是“0”。因此,在解析“正号 0”时被截断,然后字符串的其余部分 ("") 被解析为一个数字,这当然不起作用。这也解释了为什么 int.Parse("00") 不是问题。尽管您无法通过控制面板将正号设置为“0”,但仍然可以通过注册表进行设置,从而导致问题。不知道帖子中用户的计算机是如何以这种错误设置结束的......

Better yet, what is the output of this on your machine:

更好的是,您的机器上的输出是什么:

Console.WriteLine(System.Globalization.NumberFormatInfo.GetInstance(null).PositiveSign);

I'm willing to bet yours prints out a 0... when mine prints out a +sign.

我敢打赌你的打印出一个0......当我的打印出一个+标志时。

I suggest checking your Control Panel > Regional and Language Optionssettings... if they appear normal, try changing them to something else than back to whatever language you're using (I'm assuming English).

我建议检查您的Control Panel > Regional and Language Options设置...如果它们看起来正常,请尝试将它们更改为其他语言而不是您使用的任何语言(我假设是英语)。

回答by laktak

Are you sure it's "0" and not "null"? What exception do you get?

你确定它是“0”而不是“null”吗?你有什么例外?

EDIT:

编辑:

Just out of curiosity, if it is really faulting on int.Parse("0"), can you try int.Parse("0", CultureInfo.InvariantCulture);?

只是出于好奇,如果它真的是 int.Parse("0") 上的错误,你能试试 int.Parse("0", CultureInfo.InvariantCulture); 吗?

Otherwise, post your query. Any joins?

否则,发布您的查询。有加盟吗?

回答by Quintin Robinson

Edit:
@Mike's response made me think that is extremely odd behavior and a simple google search yielded this result: int.Parse weird behavior

编辑:
@Mike 的回应让我认为这是非常奇怪的行为,一个简单的谷歌搜索产生了这个结果:int.Parse 奇怪的行为

An empty string would also cause this issue.

空字符串也会导致此问题。

You could check for dbnull before parsing, also it is good to validate parsed data.

您可以在解析之前检查 dbnull,也可以验证解析的数据。

You could use a default value and TryParse..

您可以使用默认值和 TryParse..

int i = -1;
if(!int.TryParse(dr["MyColumn"] as string, out i))
   //Uh Oh!

Edit:
I posted this as a comment in @Chris' answer, but if the sql datatype is int then why not just use the GetInt32method on the DataReater instead of retrieving it as a string and manual parsing it out?

编辑:
我将此作为评论发布在@Chris 的回答中,但是如果 sql 数据类型是 int 那么为什么不直接在 DataReater 上使用GetInt32方法而不是将其作为字符串检索并手动解析出来呢?

回答by J.W.

I think it's generally not considered a good idea to call Convert.ToInt32 for the value reading out of database, what about the value is null, what about the value cannot be parsed. Do you have any exception handling code here.

我认为从数据库中读取值时调用 Convert.ToInt32 通常不是一个好主意,值是 null 怎么办,值无法解析怎么办。你这里有任何异常处理代码吗?

  1. Make sure the value is not null.
  2. Check the value can be parsed before call Int32.Parse. Consider Int32.TryParse.
  3. consider use a nullable type like int? in this case.
  1. 确保该值不为空。
  2. 在调用 Int32.Parse 之前检查可以解析的值。考虑 Int32.TryParse。
  3. 考虑使用像 int 这样的可为空类型?在这种情况下。

HTH.

哈。

回答by Mcbeev

are you checking for null ?

你在检查 null 吗?

if(!dr.IsNull("FieldName")){
   int i = Convert.ToInt32(dr["FieldName"]))
}

回答by Muad'Dib

you should check dr["FieldName"] != DBNull.Value and you should use TryParse if it passes the DBNull test...

你应该检查 dr["FieldName"] != DBNull.Value 并且你应该使用 TryParse 如果它通过 DBNull 测试......

if ( dr["FieldName"] != DBNull.Value )
{
    int val = 0;
    if ( int.TryParse( dr["FieldName"], out val ) )
    {
        i = val;
    }
    else
    {
        i = 0; // or some default value
    }
}

回答by Mike

I have seen this issue crop up with .NET Double class, parsing from string "0" as well.

我已经看到这个问题出现在 .NET Double 类中,也从字符串“0”解析。

Here's the really wacky part: you can get past the issue by using a different user accountto run the program, and sometimes if you destroy and re-create the current user account on the machine, it will run fine.

这是真正古怪的部分:您可以通过使用不同的用户帐户来运行程序来解决这个问题,有时如果您在机器上销毁并重新创建当前用户帐户,它会运行良好。

I have yet to track this down, but you might get past it this way at least.

我还没有追踪到这一点,但你至少可以通过这种方式过去。

回答by harpo

This is way out of left field, but check your localization settings. I had a number of "input string was not in a correct format" when I moved a web site to a Canadian server. The problem was in a DateTime.Parse method, and was fixed by setting the culture to "en-US".

这是超出左侧字段的方法,但请检查您的本地化设置。当我将网站移动到加拿大服务器时,我遇到了许多“输入字符串格式不正确”的问题。问题出在 DateTime.Parse 方法中,并通过将区域性设置为“en-US”来解决。

Yes, your situation is different — but hey, you never know.

是的,你的情况不同——但嘿,你永远不知道。