简体   繁体   English

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

[英]C# parse string “0” to integer

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." 奇怪的是,ReSharper还出现了许多奇怪的错误,并带有与上述代码相同的错误消息:“输入字符串的格式不正确。” (Starts before I even load a project.) (在加载项目之前就开始。)

Any ideas? 有任何想法吗? Anyone having any SP issues? 有人有SP问题吗? I did try to make sure all my SPs were up-to-date when I got the machine. 买机器时,我确实尝试确保所有SP都是最新的。

EDIT: I understand how to use Try.Parse and error-handling. 编辑:我知道如何使用Try.Parse和错误处理。 The code here is simplified. 此处的代码已简化。 I am reading test cases from a database table. 我正在从数据库表中读取测试用例。 This column has only 0, 1, and 2 values. 该列只有0、1和2个值。 I have confirmed that. 我已经确认了。 I broke this down putting the database field into a string variable s and then trying int.Parse(s). 我将数据库字段放入字符串变量s中,然后尝试使用int.Parse(s)。 The code worked earlier this week and the database has not changed. 该代码在本周早些时候有效,数据库未更改。 The only thing that has changed is my environment. 唯一改变的是我的环境。

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. 解决方案是强制重置我的语言设置。

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'. 基本上,问题在于HKEY_CURRENT_USER \\ Control Panel \\ International下的sPositiveSign值设置为0,这意味着正号为'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. 因此,在解析“正号0”时,将其截断,然后将字符串的其余部分(“”)解析为数字,这当然是行不通的。 This also explains why int.Parse("00") wasn't a problem. 这也解释了为什么int.Parse(“ 00”)不是问题。 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. 尽管无法通过“控制面板”将正号设置为“ 0”,但是仍然可以通过注册表进行设置,从而导致问题。 No idea how the computer of the user in the post ended up with this wrong setting... 不知道帖子中用户的计算机是如何以这种错误的设置结束的...

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 Options settings... 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设置...如果它们显示正常,请尝试将其更改为不同于您使用的任何语言的其他语言(我假设是英语)。

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. 我认为调用Convert.ToInt32以从数据库中读取值通常不是一个好主意,该值是null,该值不能解析。 Do you have any exception handling code here. 您在这里有任何异常处理代码吗?

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

HTH. HTH。

Are you sure it's "0" and not "null"? 您确定它是“ 0”而不是“ null”吗? What exception do you get? 你有什么例外?

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? 有参加吗?

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的回应让我认为这是极其奇怪的行为,一个简单的Google搜索就产生了以下结果: 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 GetInt32 method on the DataReater instead of retrieving it as a string and manual parsing it out? 我在@Chris的答案中将其发布为注释,但是如果sql数据类型为int,为什么不直接在DataReater上使用GetInt32方法而不是将其作为字符串检索并手动解析呢?

you should check dr["FieldName"] != DBNull.Value and you should use TryParse if it passes the DBNull test... 您应该检查dr [“ FieldName”]!= DBNull.Value,并且如果它通过DBNull测试,则应该使用TryParse。

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

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 account to 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. 我还没有找到答案,但是您至少可以这样解决。

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. 是的,您的情况有所不同-但是,您永远不会知道。

are you checking for null ? 您要检查null吗?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM