The compiler first tries to evaluate the right-hand expression:
GetBoolValue() ? 10 : null
The 10
is an int
literal (not int?
) and null
is, well, null
. There's no implicit conversion between those two hence the error message.
If you change the right-hand expression to one of the following then it compiles because there is an implicit conversion between int?
and null
(#1) and between int
and int?
(#2, #3).
GetBoolValue() ? (int?)10 : null // #1
GetBoolValue() ? 10 : (int?)null // #2
GetBoolValue() ? 10 : default(int?) // #3
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…