我只是想知道为什么以下代码不起作用(请记住我将 age
设置为可为空):
myEmployee.age = conditionMet ? someNumber : null;
但以下工作正常:
if(conditionMet)
{
myEmployee.age = someNumber;
}
else
{
myEmployee.age = null;
}
为什么我不能在条件运算符中将值设置为 null??我代码中的所有这些 if
语句都不好。
谢谢。
最佳答案
两边的类型必须相同(或者可以隐式转换):
myEmployee.age = conditionMet ? someNumber : (int?)null;
来自docs :
Either the type of first_expression and second_expression must be the same, or an implicit conversion must exist from one type to the other.
关于C#.net 无法将 null 分配给内联 if 语句中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10283237/