问题描述
- 盒装为空的基础类型的可投以枚举,但盒装枚举类型的不能转换可空类型。
同样,
- 盒装为空的枚举的可投以基本类型,但是盒装的基础类型的不能转换以可空的枚举。
的好吧,我知道盒装可空类型是不是来形容它的最好方式,但它的问题的缘故。我知道那就是变得越来越盒装基础值类型。的
我将举例证明这一点。假设我有一个枚举
与 INT
作为基础类型。
枚举性别{男,女}
案例一
诠释? I = 1;
对象o = I;
性别E =(性别)O; //成功
//但是
性别E = Sex.Male;
对象o = E;
诠释? I =(INT)O; //无效转换
案例二:
性爱? E = Sex.Male;
对象o = E;
INT I =(INT)O; //成功
//但是
INT I = 1;
对象o = I;
性别? E =(性别)O; //无效转换
简而言之,
(枚举)INT? - >成功
(INT?)枚举 - >反向失败
(INT)枚举? - >成功
(枚举?)INT - >反向失败
或在更简单来说,
Now I do know that once you box a value type, it can be cast back only to the original type. But since by C# rules, a boxed int
can be cast to enum
and a boxed enum
can be cast to int
, and a boxed int
to int?
and a boxed int?
to int
, I was looking for a consistent understanding of other scenarios as well, ie the ones listed above. But I dont get the logic. For one, I feel if they all failed or if they all succeeded, it made more sense to developers. Two, even the successful casts look a little odd. I mean since a value type can be implicitly cast to its nullable equivalent (and not the other way around), a cast to nullable should anyway succeed, but with the current implementation a nullable type is being successfully cast to non-nullable which can even fail if the former had a null value. Had this whole thing been other way around, it would have been easier comprehending. An example like:
Sex? e = null;
object o = e;
int i = (int)o; //succeeds, but sure to explode on cast
//but
int i = 1;
object o = i;
Sex? e = (Sex?)o; //invalid cast, even though its always a safe cast
Questions:
So what C# rule is letting this happen?
Is there a simple way I can remember this?
I think this is a subtlety of the unbox
and unbox.any
IL instructions.
From ECMA 335, section III.4.32 (unbox
operation - unbox.any
is similar)
So for example, in this case:
Sex e = Sex.Male;
object o = e;
int? i = (int?)o;
it fails entirely correctly - because valuetype is Nullable<int>
and the value of obj is not a boxed int
. The "verifier-assignable-to" part doesn't apply for the Nullable<T>
case.
I doubt that any of this behaviour is described in the C# specification, unfortunately - I don't think the unboxing behaviour from "boxed int
" to "enum with an underlying type of int
" is described, as far as I can see, which is a sort of prerequisite to then including nullability in the mix.
这篇关于可空盒装基础类型可以转换为枚举,但盒装枚举类型不能转换为可空类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!