输入的字符串格式不正确 [英] input string was not in the correct format error
问题描述
我不知道为什么会发生此错误,任何人都可以告诉我
I have no idea why this error is occurring can anyone tell me
long? Max = row["MAX"].ToString() != null || row["MAX"].ToString() != "" ? long.Parse(row["MAX"].ToString()) : (long?)null;
推荐答案
如果您要检查 row ["MAX"]
是否为 null
,则应进行更改检查到:
If your intent is to check if row["MAX"]
is null
then you should change that check to:
row["MAX"] != null
这是因为 ToString()
的返回值永远不会是 null
,但是如果在上调用它,则会抛出
对象(然后 NullReferenceException
> null row ["MAX"].ToString()
对于 null
对象将失败).
This because return value of ToString()
is never null
but it'll throw a NullReferenceException
if you invoke it on a null
object (then row["MAX"].ToString()
will fail for null
objects).
在您的情况下,它不是 null
,而是空字符串,您可以更改为:
In your case it's not null
but it's an empty string, you may change to this:
long? Max = (row["MAX"] != null && row["MAX"].ToString() != "")
? long.Parse(row["MAX"].ToString()) : (long?)null;
但是正如您所看到的那样,它并不是很可读,我将更改(跳过任何其他验证)为:
But as you can see it's not really readable, I would change (skipping any other validation) to:
long? Max = null;
if (row["MAX"] != null && row["MAX"].ToString() != "")
Max = Long.Parse(row["MAX"].ToString());
编辑,如 Jota WA的答案(我认为是正确的)中指出的那样,如果您的第 object
行来自数据库(实际上我们不知道其类型,因此我们只能猜测并假设它是 object
的字典),您可能会有 DBNull.Value
而不是 null
.在这种情况下, row ["MAX"]!= null
为 false
,但是第二次检查 row ["MAX"].ToString()会捕获此条件!="
.也就是说,如果这是您的情况,并且您确定自己的字典不包含任何 real null
值,则可以使其更简单:
EDIT as pointed out in Jota WA's answer (which I consider right) if your row object
comes from a database (actually we don't know its type so we can just guess and assume it's kind of dictionary of object
) you may have DBNull.Value
instead of null
. In this case row["MAX"] != null
is false
but this condition is catched by 2nd check row["MAX"].ToString() != ""
. That said if this is your case and you're sure your dictionary doesn't contain any real null
value you may make it simpler:
if (row["MAX"].ToString() != "")
甚至:
if (row["MAX"] != DBValue.Null)
我想您可能需要 add 验证,然后应使用 TryParse
这样:
I suppose you may need to add validation then you should use TryParse
like this:
// Here you may handle row["MAX"] == null case, if it may happen
string MaxText = row["MAX"].ToString();
long? Max = null;
if (MaxText != "")
{
long value;
if (long.TryParse(MaxText, out value))
{
// You may add more validation here, for example
// to check value's range
Max = value;
}
}
这篇关于输入的字符串格式不正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!