为什么集合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值,然后Select将int值转换为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,然后转换int为int?.)
| 归档时间: |
|
| 查看次数: |
2339 次 |
| 最近记录: |