为什么<enum>的集合无法转换为<int?>?

Hom*_*mam 10 c# linq casting

为什么集合enum无法投射到int?

enum Test { A = 1, B = 2 };

int? x = (int?)Test.A; // Valid

var collection1 = new[] { Test.A }.Cast<int>().ToList();

// InvalidCastException has thrown (Specified cast is not valid.)    
var collection2 = new[] { Test.A }.Cast<int?>().ToList(); 
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 14

Cast方法只能执行装箱/拆箱转换,引用转换以及枚举类型与其基础整数类型之间的转换.取消装箱必须是正确的类型 - 它不能取消装入可以为空的类型(与C#转换不同).

var collection1 = new[] { Test.A }.Cast<int>()
                                  .Select(x => (int?) x)
                                  .ToList();
Run Code Online (Sandbox Code Playgroud)

对于每个值,Cast将从盒装enum值中取消框到int值,然后Selectint值转换为int?值.

在这种情况下,你可以逃避:

var collection1 = new[] { Test.A }.Select(x => (int?) x)
                                  .ToList();
Run Code Online (Sandbox Code Playgroud)

即没有Cast步骤.但是,如果您有一个数组,不起作用object:

// Fails
var collection1 = new object[] { Test.A }.Select(x => (int?) x)
                                         .ToList();
Run Code Online (Sandbox Code Playgroud)

您不能将装箱的枚举值取消装入可以为空的int值.Cast然而,该版本仍适用于该情况,因为它拆分了两个步骤(首先拆箱int,然后转换intint?.)

  • 也可以通过在select中输出两次来避免`Cast <>()`:`Select(x =>(int?)(int)x)`.但是,如果集合仅实现非泛型IEnumerable,则需要`Cast <>()`. (2认同)