Why is a generic type constrained by 'Enum' failing to qualify as a 'struct' in C# 7.3?

后端 未结 1 1592
渐次进展
渐次进展 2020-12-16 17:22

If I have a generic interface with a struct constraint like this:

public interface IStruct where T : struct { }

I can

相关标签:
1条回答
  • 2020-12-16 17:29

    This issue is strange (arguably), but expected, behavior.

    The class System.Enum itself could be supplied as the type of T. Being a class, System.Enum is of course not a struct!

    public class MCVE<T> where T : Enum { }
    public class MCVE2 : MCVE<Enum> { }
    

    As explained by contributor HaloFour:

    This is an odd behavior by the CLR itself. System.Enum is a class, but every type that derives from System.Enum is a struct. So a constraint on System.Enum by itself doesn't imply struct since you could pass System.Enum as the generic type argument...

    It is weird, but it was easier to simply remove the imposed limitation on the compiler than to argue over different syntax for "enum" constraints that might have different behavior.

    The solution is to make it your standard practice to constrain to struct, Enum when you wish to constrain concrete types to being any specific enumeration. If additionally you wish to accept the class System.Enum as your generic type, only then would you constrain to Enum.

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