C# 为什么这个条件语句不起作用,而似乎做同样事情的if语句起作用了吗?
我有这个财产:C# 为什么这个条件语句不起作用,而似乎做同样事情的if语句起作用了吗?,c#,conditional-statements,C#,Conditional Statements,我有这个财产: int? firstClientID; 为什么会这样 firstClientID = dataRow.IsFirstClientIDNull() ? null : (int.TryParse(dataRow.FirstClientID, out tempInt) ? tempInt : 0);
int? firstClientID;
为什么会这样
firstClientID = dataRow.IsFirstClientIDNull()
? null
: (int.TryParse(dataRow.FirstClientID, out tempInt)
? tempInt
: 0);
不编译是因为
无法确定条件语句的类型,因为没有
null和int之间的隐式转换
而且
if (dataRow.IsFirstClientIDNull())
firstClientID = null;
else if (int.TryParse(dataRow.FirstClientID, out tempInt))
firstClientID = tempInt;
else
firstClientID = 0;
工作?他们似乎做了同样的事情。来自
第一个_表达式和第二个_表达式的类型必须相同,或者必须存在从一种类型到另一种类型的隐式转换
i、 e.您需要确保条件运算符的两个分支返回相同的类型(即,通过强制转换可为null
)
(条件运算符实际上与
if/then else
分支不同,因为条件运算符必须返回相同类型的数据,而if
可以在分支的每个分支中执行任何操作,对类型兼容性没有限制)该属性应该是firstClientId
?。因为,除此之外,它在这里没有什么价值。
firstClientID = dataRow.IsFirstClientIDNull()
? (int?)null
: (int.TryParse(dataRow.FirstClientID, out tempInt)
? tempInt
: 0);