问题
Why do we need explicit cast in second statement?
bool? a = null;
bool b = false;
bool c = true;
1.)
if(b || c)
a = b;
else
a = null;
2.) a = (b || c)?(Nullable<bool>)b:null;
回答1:
The conditional operator is an expression, thus it needs a return type - also both cases have to have the same return type. In your case, there is no way of determining the return type automatically, thus you need to cast.
回答2:
To add to Femaref, equivalent "if" code will be something like
private static bool? Assign(bool b, bool c)
{
if (b || c)
{
return b;
}
else return null;
}
...
a = Assign (b,c)
Note the bool? return type. This is what's happening in the conditional operator statement
来源:https://stackoverflow.com/questions/5707889/c-sharp-nullable-in-conditional-statement