1

suppose I have an enum

[Flags]
public enum E { 
    zero = 0,
    one = 1
}

then I can write

E e;
object o = 1;
e = (E) o;

and it will work.

BUT if I try to do that at runtime, like

(o as IConvertible).ToType(typeof(E), null)

it will throw InvalidCastException.

So, is there something that I can invoke at runtime, and it will convert from int32 to enum, in the same way as if I wrote a cast as above?

4

3 に答える 3

4

object o = 1;
object z = Enum.ToObject(typeof(E), o); 

于 2008-12-06T00:19:18.060 に答える
0

使用することもできます

Enum.Parse(typeof(E), (int)o)
于 2008-12-07T05:22:47.760 に答える
0

How does the variable look like that you save the result of that conversion in? I.e. with which type do you declare it?

If you want to have an object variable, make it so. Instead of null, use Activator.CreateInstance to create a default instance of the enum:

object o = Activator.CreateInstance(typeof(E));
于 2008-12-05T23:32:42.350 に答える