InvalidCastException试图从一个boxed int转换为一个可空的枚举 [英] InvalidCastException trying to cast from a boxed int to a nullable enum
问题描述
我有一个枚举 Foo
:
public enum Foo {Alpha,Bravo,Charlie}
如果我试图从盒装的 int
到 Foo?
,我得到 InvalidCastException
:
var x =(Foo?)(object)1;
这让我做了一些实验...
var x =(Foo)(object)1; // succeeds
var x =(long)(object)1; // failed
var x =(long?)(object)1; // failed
var x =(long)1; // succeeds
var x =(long?)1; // succeeds
var x =(int)(object)1; // succeeds
var x =(int?)(object)1; // succeeds
这告诉我的是,你可以从一个盒子 int
转换为枚举,而不是长
,并且不能除了 int?
。
顺便说一句,我把 int
转换为对象
的原因是我真的试图从 int
到一个通用参数 TValue
,如下所示:
var x =(TValue)(object)1;
-
为什么可以从一个盒装的
int
转换为枚举,而不是可空的枚举(而不是long
也不是long?
)? -
重写
var x =(TValue)(object)1;
最简单的方法是编译,在运行时工作,并且是执行的(假设TValue
在运行时确定为Foo?
)
要回答第一个问题,只有当框值是枚举的底层类型时,才可以从一个框值转换为枚举。您是否已宣布
enum Foo:byte {...
$ p
要回答第二个问题,请尝试
/ p>
var x =(TValue)Enum.ToObject(typeof(TValue),1);
这包括拳击,如果你需要一个不会包装的解决方案,它会更复杂。
I have an enum,
Foo
:public enum Foo { Alpha, Bravo, Charlie }
If I attempt the following cast from a boxed
int
to aFoo?
, I get anInvalidCastException
:var x = (Foo?)(object)1;
This led me to some experimentation...
var x = (Foo)(object)1; // succeeds var x = (long)(object)1; // fails var x = (long?)(object)1; // fails var x = (long)1; // succeeds var x = (long?)1; // succeeds var x = (int)(object)1; // succeeds var x = (int?)(object)1; // succeeds
What this tells me is that you can cast from a boxed
int
to an enum but not to along
, and you cannot convert from a boxedint
to any kind of nullable except anint?
.By the way, the reason I'm casting the
int
toobject
first is that I'm really trying to cast from anint
to a generic parameterTValue
, like this:var x = (TValue)(object)1;
If I didn't have
(object)
, it wouldn't compile. (See this blog post by Eric Lippert for details.)Questions
Why can you convert from a boxed
int
to an enum, but not to a nullable enum (and not to along
nor along?
)?What's the easiest way to rewrite
var x = (TValue)(object)1;
so that it compiles, works at runtime, and is performant (assumingTValue
is determined to be aFoo?
at runtime)?
解决方案To answer the first question, you can convert from a boxed value to an enum only if the boxed value is of the enum's underlying type. Had you declared
enum Foo : byte { ...
you would not be able to cast from boxed int to Foo.
To answer the second question, try
var x = (TValue)Enum.ToObject(typeof(TValue), 1);
This involves boxing, though; if you need a solution that won't box, it will be more complicated.
这篇关于InvalidCastException试图从一个boxed int转换为一个可空的枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!