问题
I would like to do something like this :
int? l = lc.HasValue ? (int)lc.Value : null;
where lc is a nullable enumeration type, say EMyEnumeration?. So I want to test if lc has a value, so if then give its int value to l, otherwise l is null. But when I do this, C# complains that 'Error type of conditional expression cannot be determined as there is no implicit conversion between 'int' and ''.
How can I make it correct? Thanks in advance!!
回答1:
You have to cast null
as well:
int? l = lc.HasValue ? (int)lc.Value : (int?)null;
By the way, that's one of the differences between the conditional operator and an if-else
:
if (lc.HasValue)
l = (int)lc.Value;
else
l = null; // works
The relevant C# specification is 7.14 Conditional operator:
The second and third operands, x and y, of the ?: operator
control the type of the conditional expression.
- If x has type X and y has type Y then
- If an implicit conversion (§6.1) exists from X to Y, but not from Y to X, then Y is the type of the conditional expression.
- If an implicit conversion (§6.1) exists from Y to X, but not from X to Y, then X is the type of the conditional expression.
- Otherwise, no expression type can be determined, and a compile-time error occurs.
Since int
is not convertible to null
implicitly and vice-versa you get a compiler error. But you could also cast the enum
to int?
instead of int
which is convertible. Then the compiler can derive the type and it'll compile:
int? l = lc.HasValue ? (int?)lc.Value : null; // works also
or, as Sergey has mentioned in his answer, directly:
int? l = (int?)lc;
回答2:
Simply cast your nullable enum value to nullable integer:
int? l = (int?)lc;
Due to C# specification 6.2.3 Explicit nullable conversions:
Evaluation of a nullable conversion based on an underlying conversion from S to T proceeds as follows if the nullable conversion is from S? to T?:
- If the source value is null (HasValue property is false), the result is the null value of type T?.
- Otherwise, the conversion is evaluated as an unwrapping from S? to S, followed by the underlying conversion from S to T, followed by a wrapping from T to T?.
回答3:
You should this:
int? l = lc.HasValue ? (int)lc.Value : (int?)null;
来源:https://stackoverflow.com/questions/21041519/convert-between-nullable-int-and-int