相关疑难解决方法(0)

应用于通用枚举集合的Cast <int> .Cast <int?>会导致无效的强制转换异常

enum Gender { Male, Female }

var k = new[] { Gender.Male }.Cast<int>().ToList().Cast<int?>().ToList(); //alright

var p = new[] { Gender.Male }.Cast<int>().Cast<int?>().ToList(); //InvalidCastException
Run Code Online (Sandbox Code Playgroud)

第二种情况的原因是什么?我知道我不能投了盒装enum,以int?直接,但我做了两个阶段铸造,即Cast<int>.Cast<int?>应工作.

编辑:

考虑到以下工作,这是令人惊讶的:

object o = Gender.Male;
int i = (int)o; // so here the cast is not to an entirely different type, which works
Run Code Online (Sandbox Code Playgroud)

c# enums casting type-conversion

7
推荐指数
1
解决办法
178
查看次数

标签 统计

c# ×1

casting ×1

enums ×1

type-conversion ×1