【问题标题】:enum[] is IEnumerable<int> returns true in a generic methodenum[] is IEnumerable<int> 在泛型方法中返回 true
【发布时间】:2013-11-29 20:33:48
【问题描述】:

这是对这个问题的跟进:Cast<int>.Cast<int?> applied on generic enum collection results in invalid cast exception

enum Gender { Male, Female }

Gender g = Gender.Male;

bool b = g is int; // false, alright no issues
b = new[] { g } is IEnumerable<int>; // false, alright no issues
b = Is<Gender, int>(g); //false, alright no issues
b = Is<Gender[], IEnumerable<int>>(new[] { g }); // true, why on earth !!!

static bool Is<S, T>(S s)
{
    return s is T;
}

为什么Gender[] is IEnumerable&lt;int&gt; 在一般情况下返回true?尤其是当它们类型不兼容时?

IEnumerable<int> c = new[] { Gender.Male }; //not compilable

它在我链接的问题中绊倒了我!我认为这个问题是链接问题问题的症结所在。


对于感兴趣的人,这是数组(不是真正的枚举)的极端案例。关注答案中的Eric Lippert's blog 文章以了解更多关于这种极端情况的信息。例如,List&lt;T&gt; 不会发生这种情况:

b = Is<List<Gender>, IEnumerable<int>>(new List<Gender> { g }); // false, rightly

【问题讨论】:

    标签: c# generics enums typechecking


    【解决方案1】:

    我认为这是is 的C# 定义与CLI 的isinst 定义不同的情况之一,后者在检查数组分配兼容性时显然将枚举视为其基础基本类型。 (Eric Lippert 写了一个 blog post 解释了为什么 CLI 将 uint[] 视为 int[] 而不是 C#;我怀疑这里也适用相同的解释。)您甚至不需要泛型来演示:

    Gender g = Gender.Male;
    Console.WriteLine(new[] { g } is IEnumerable<int>); // False
    Console.WriteLine((object)new[] { g } is IEnumerable<int>); // True
    

    第一个is 表达式在编译时优化为false,因为C# 编译器“知道”Gender[] 不是IEnumerable&lt;int&gt;。第二个is 表达式生成一个isinst 指令,该指令在运行时 进行评估。引用 Eric Lippert 的话:

    很遗憾,C# 和 CLI 规范在这个小问题上存在分歧,但我们愿意忍受这种不一致。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-07-17
    • 2016-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多