且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C# 将 int 类型的对象强制转换为可为空的枚举

更新时间:2022-06-07 03:47:29

怎么样:

MyEnum? val = value == null ? (MyEnum?) null : (MyEnum) value;

从装箱的 intMyEnum 的转换(如果 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.