what's the runtime equivalent of c# 'bracketed' type cast

﹥>﹥吖頭↗ 提交于 2019-12-11 09:16:44

问题


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?


回答1:



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




回答2:


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));



回答3:


You can also use

Enum.Parse(typeof(E), (int)o)


来源:https://stackoverflow.com/questions/345506/whats-the-runtime-equivalent-of-c-sharp-bracketed-type-cast

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!