enum[] is IEnumerable returns true in a generic method

前端 未结 1 2159
故里飘歌
故里飘歌 2021-02-19 03:19

This is a followup to this question: Cast.Cast applied on generic enum collection results in invalid cast exception

enum Gender { Male, Fe         


        
1条回答
  •  一整个雨季
    2021-02-19 04:10

    I think this is one of those cases where the C# definition of is differs from the CLI's definition of isinst, which evidently treats enums as their underlying base type when checking for array assignment compatibility. (Eric Lippert wrote a blog post that explains why uint[] is treated as an int[] by the CLI but not by C#; I suspect the same explanation applies here.) You don't even need generics to demonstrate:

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

    The first is expression is optimized to false at compile time because the C# compiler "knows" Gender[] isn't an IEnumerable. The second is expression generates an isinst instruction which is evaluated at run time. Quoting Eric Lippert:

    It is unfortunate that C# and the CLI specifications disagree on this minor point but we are willing to live with the inconsistency.

    0 讨论(0)
提交回复
热议问题