可空int和INT之间的转换 [英] Convert between nullable int and int
问题描述
我愿做这样的事情:
int? l = lc.HasValue ? (int)lc.Value : null;
,其中LC是可空枚举类型,说EMyEnumeration?所以我想测试是否LC有一个值,所以如果再给予其int值升,否则l为null。但我这样做的时候,C#抱怨道:条件表达式的错误类型不能被确定为之间不存在隐式转换'廉政'和''。
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!!
推荐答案
您已经投空
,以及
int? l = lc.HasValue ? (int)lc.Value : (int?)null;
顺便说一句,这是的的条件运算符和的if-else
:
if (lc.HasValue)
l = (int)lc.Value;
else
l = null; // works
有关C#规范的 7.14条件运算符
第二个和第三个操作数,x和y的?:运营商
控制条件表达式的类型。
The second and third operands, x and y, of the ?: operator
control the type of the conditional expression.
- 如果x具有X型和Y具有Y型则
- 如果隐式转换(第6.1节)从X到Y存在,但不能从Y到X,那么Y就是条件表达式的类型。
- 如果(第6.1节)从Y到存在的隐式转换X,但不能从X到Y,则X就是条件表达式的类型。
- 否则,毫无表情的类型可确定和编制─发生错误。
- 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.
由于
INT
是无法转换为空
含蓄,反之亦然,你得到一个编译错误。但你也可以施放枚举
到INT?
而不是INT
其中是的敞篷车。那么编译器可以推导出类型,它就会编译:Since
int
is not convertible tonull
implicitly and vice-versa you get a compiler error. But you could also cast theenum
toint?
instead ofint
which is convertible. Then the compiler can derive the type and it'll compile:int? l = lc.HasValue ? (int?)lc.Value : null; // works also
或像谢尔盖在他的answer 直接:
or, as Sergey has mentioned in his answer, directly:
int? l = (int?)lc;
这篇关于可空int和INT之间的转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!