InvalidCastException试图从一个boxed int转换为一个可空的枚举 [英] InvalidCastException trying to cast from a boxed int to a nullable enum

查看:189
本文介绍了InvalidCastException试图从一个boxed int转换为一个可空的枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个枚举 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; 

如果我没有(object),它不会编译。 (请参阅此




  1. 为什么可以从一个盒装的 int 转换为枚举,而不是可空的枚举(而不是 long 也不是 long?)?


  2. 重写 var x =(TValue)(object)1; 最简单的方法是编译,在运行时工作,并且是执行的(假设 TValue 在运行时确定为 Foo?



解决方案

要回答第一个问题,只有当框值是枚举的底层类型时,才可以从一个框值转换为枚举。您是否已宣布

  enum Foo:byte {... 
要回答第二个问题,请尝试

/ 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 a Foo?, I get an InvalidCastException:

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 a long, and you cannot convert from a boxed int to any kind of nullable except an int?.

By the way, the reason I'm casting the int to object first is that I'm really trying to cast from an int to a generic parameter TValue, 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

  1. Why can you convert from a boxed int to an enum, but not to a nullable enum (and not to a long nor a long?)?

  2. What's the easiest way to rewrite var x = (TValue)(object)1; so that it compiles, works at runtime, and is performant (assuming TValue is determined to be a Foo? 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆