C#.net 无法将 null 分配给内联 if 语句中的变量

标签 c# .net

我只是想知道为什么以下代码不起作用(请记住我将 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/

相关文章:

c# - 如何延迟 Silverlight ViewModel 类中的数据查询?

c# - 在 xaml 中访问 DisplayName

c# - 如何从数组中的文件中写入单词?

c# - 在具有母版页的页面上查找控件

c# - 如何在 C# 中为图像设置动画

.NET 2.0 中的 C# ToArray 函数

c# - 从 WinForms 应用程序检查 .Net 框架版本

.net - 带有 .NET Core 应用程序的 Google API

c# - C# 中从 JSON 读取特定值

c# 应用程序运行 matlab 错误使用 cd 太多输入参数