加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 20:47:25 所属栏目:百科 来源:网络整理
导读:我只是想知道为什么以下代码不起作用(请记住,我将年龄设置为可以为空): myEmployee.age = conditionMet ? someNumber : null; 但以下工作正常: if(conditionMet){ myEmployee.age = someNumber;}else{ myEmployee.age = 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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读