2017-05-08 54 views
-1

我有時可以將null分配到int?但不在? :內,爲什麼?不能設置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 */; 
+0

因爲?:運算符中的兩個表達式都應該具有相同的類型,或者應該存在從一個到另一個的隱式轉換。 int(1)和null不是這種情況。 – Evk

回答

5

the documentation

要麼first_expression和second_expression的類型必須是相同的,或隱式轉換必須從一個類型到 其他。

所以,在b = (a != null) ? 1 : null類型的第一個參數是int,和第二個參數是null,違反上述規則。

在第二種情況下,int可以隱式轉換爲(int?)null,這就是它的工作原理。

+0

只需添加,一旦將'null'轉換爲'(int?)null',現在就存在一個隱式轉換。 –