无法设置int?在?内部为null:运算符

ast*_*ght -1 c#

我有时可以分配null到int?但不是里面? :,为什么呢?

例

int? a;  // good
    int? b; // good 

    a = null;  // why is this allowed?
    b = (a != null) ? 1 : null /* and this not allowed? */; 

    b = (a != null) ? 1 : (int?)null /* this is a fix */; 
Run Code Online (Sandbox Code Playgroud)

Ale*_*nda 5

从文档:

first_expression和second_expression的类型必须相同,或者从一种类型到另一种类型必须存在隐式转换.

因此,在b = (a != null) ? 1 : null第一个参数的类型是int,第二个参数是null,这违反了上述规则.

在第二种情况下,int可以隐式转换为(int?)null,这就是它的工作原理.