Convert.ToInt32适用于if语句,但不适用于?操作者

时间:2013-02-26 20:51:45

标签: c# visual-studio-2010

由于某种原因,Visual Studio在此行中存在问题:

MandatoryStakeholder.SupportDocTypeID = (String.IsNullOrEmpty(allIDValues[1]) || (allIDValues[1] == "0")) ?  null : Convert.ToInt32(allIDValues[1]);

特别是Convert.ToInt32(allIDValues[1])部分。错误是“C#:这些类型不兼容'null':'int'”

但是如果我用下面的方法模仿那个逻辑就没有问题:

if (string.IsNullOrEmpty(allIDValues[1]) || Convert.ToInt32(allIDValues[1]) == 0)
                stakeHolder.SupportDocTypeId = null;
            else
                stakeHolder.SupportDocTypeId = Convert.ToInt32(allIDValues[1]);

MandatoryStakeholder.SupportDocTypeID的类型为int?。不知道为什么我可以在if语句中将字符串转换为int,但不能用?操作

3 个答案:

答案 0 :(得分:3)

? null更改为? (int?) null

MandatoryStakeholder.SupportDocTypeID = (String.IsNullOrEmpty(allIDValues[1]) || (allIDValues[1] == "0")) ?  (int?)null : Convert.ToInt32(allIDValues[1]);

答案 1 :(得分:3)

尝试将null转换为int?

MandatoryStakeholder.SupportDocTypeID = 
    (String.IsNullOrEmpty(allIDValues[1]) || (allIDValues[1] == "0")) ?  
       (int?)null : 
       Convert.ToInt32(allIDValues[1]);

答案 2 :(得分:2)

那是因为在if版本中,

 stakeHolder.SupportDocTypeId = Convert.ToInt32(allIDValues[1]);

正在静默转换为

 stakeHolder.SupportDocTypeId = new int?(Convert.ToInt32(allIDValues[1]));

要获得三元等价物,您需要将代码更改为:

MandatoryStakeholder.SupportDocTypeID = (String.IsNullOrEmpty(allIDValues[1]) || (allIDValues[1] == "0")) ?  null : new int?(Convert.ToInt32(allIDValues[1]));
相关问题