为什么这条线不起作用用户。年龄 = (结果[11] == 字符串。空) ?(国际?null : Int32.Parse(result[11])



假设result[11] == string.Empty(即result[11] = ""(

if (result[11] == string.Empty) // this block works fine
{
    user.Age = Int32.Parse(result[11]);
}
else
{
    user.Age = null;
}
// the following line will throw exception
user.Age = (result[11] == string.Empty) ? (int?) null : 
                                          Int32.Parse(result[11]);

System.FormatException未处理消息=输入字符串的格式不正确。来源=mscorlibStackTrace:在System.Number.StringToNumber(字符串str、NumberStyles选项、NumberBuffer&Number、>>>NumberFormatInfo信息、布尔值parseDecimal(位于System.Number.ParseInt32(字符串s,NumberStyles样式,NumberFormatInfo信息(在System.Int32.解析(字符串s(

对我来说,以上两个区块是相同的。那为什么第一个有效,而第二个无效呢?

这些块不相同。

if (result[11] == string.Empty) // this block works fine
{
    user.Age = Int32.Parse(result[11]);
}

该块实际上不应该工作,因为该块只会解析一个空字符串。切换"if"块和"else"块中的代码,它将与您的三元"?:"运算符相同。

我试过这个:

        var value = "";
        int? age;
        if (value != string.Empty)
        {
            age = Int32.Parse(value);
        }
        else
        {
            age = null;
        }

        age = (value == string.Empty) ? (int?)null : Int32.Parse(value);

并且它工作良好(我已经在第一个if中将==改变为!=(。

您试图解析为Integer的结果不是有效的Integer,因此出现了异常。相反,请执行以下操作。

if (!String.IsNullOrEmpty(result[11]))
{
    if (!Int32.TryParse(result[11], out user.Age))
        user.Age = null; // not really needed
}

每个人都回答了如何将无效字符串解析为整数。他们是对的。然而,显然人们忽略了您的代码是不等价的,因为您颠倒了三元子句。这将是您的等效代码:

//if this is your code:
if (result[11] == string.Empty) // this block works fine
{
    user.Age = Int32.Parse(result[11]);
}
else
{
    user.Age = null;
}
//This is your equivalent ternary. You have inverted here
user.Age = (result[11] == string.Empty) ? Int32.Parse(result[11]) : 
                                          null;

result[i]可能返回'object',ergo-cast:

     (string) result[i] == ....
     Int.Parse(  (string) result[i] )

最新更新