c#“括号”的运行时等效项是什么? 类型转换
假设我有一个枚举,
[Flags]
public enum E {
zero = 0,
one = 1
}
那么我可以编写
E e;
object o = 1;
e = (E) o;
并且它会起作用。
但如果我尝试在运行时执行此操作,
(o as IConvertible).ToType(typeof(E), null)
则会抛出 InvalidCastException。
那么,是否有一些东西我可以在运行时调用,并且它将从 int32 转换为枚举,就像我编写上面的强制转换一样?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
保存转换结果的变量是什么样的? 即你用哪种类型声明它?
如果你想有一个对象变量,那就这样吧。 使用
Activator.CreateInstance
来创建枚举的默认实例,而不是null
: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
, useActivator.CreateInstance
to create a default instance of the enum:您还可以使用
You can also use