微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

C#.net无法为内联if语句中的变量赋值null

我只是想知道为什么以下代码不起作用(请记住,我将年龄设置为可以为空):

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.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐