C# 将 int 类型的对象强制转换为可为空的枚举 [英] C# cast object of type int to nullable enum
问题描述
我只需要能够将对象转换为可为空的枚举.对象可以是 enum、null 或 int.谢谢!
I just need to be able to cast an object to nullable enum. Object can be enum, null, or int. Thanks!
public enum MyEnum { A, B }
void Put(object value)
{
System.Nullable<Myenum> val = (System.Nullable<MyEnum>)value;
}
Put(null); // works
Put(Myenum.B); // works
Put(1); // Invalid cast exception!!
推荐答案
怎么样:
MyEnum? val = value == null ? (MyEnum?) null : (MyEnum) value;
从装箱的 int
到 MyEnum
的转换(如果 value
为非空),然后使用从 MyEnum 的隐式转换
到 Nullable
.
The cast from boxed int
to MyEnum
(if value
is non-null) and then use the implicit conversion from MyEnum
to Nullable<MyEnum>
.
没关系,因为您可以从枚举的装箱形式拆箱到其底层类型,反之亦然.
That's okay, because you're allowed to unbox from the boxed form of an enum to its underlying type, or vice versa.
我相信这实际上是一种转换,不保证 C# 规范可以正常工作,但 保证 CLI 规范可以正常工作.所以只要你在 CLI 实现上运行你的 C# 代码(你将是 :),你会没事的.
I believe this is actually a conversion which isn't guaranteed to work by the C# spec, but is guaranteed to work by the CLI spec. So as long as you're running your C# code on a CLI implementation (which you will be :) you'll be fine.
这篇关于C# 将 int 类型的对象强制转换为可为空的枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!