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

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

概述我只是想知道为什么以下代码不起作用(请记住,我将年龄设置为可以为空): 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.

总结

以上是内存溢出为你收集整理的C#.net无法为内联if语句中的变量赋值null全部内容,希望文章能够帮你解决C#.net无法为内联if语句中的变量赋值null所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/1226089.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-05
下一篇2022-06-05

发表评论

登录后才能评论

评论列表(0条)

    保存