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

荒凉一梦 提交于 2019-11-27 23:45:41

问题


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

public interface IStruct<T> where T : struct { }

I can supply an enumeration as my type T like so, because an enum satisfies a struct constraint:

public class EnumIsAStruct : IStruct<DateTimeKind> { }

C# 7.3 added an Enum constraint. The following code, which was previously illegal, now compiles:

public class MCVE<T> : IStruct<T> where T : struct, Enum { }

However, to my surprise, the following fails to compile:

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

...with the error

CS0453 The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'IStruct'

Why is this? I would expect a generic type constrained by Enum to be usable as a type argument where the type is constrained by struct but this doesn't seem to be the case - I am having to change my Enum constraint to struct, Enum. Is my expectation wrong?


回答1:


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.



来源:https://stackoverflow.com/questions/50294032/why-is-a-generic-type-constrained-by-enum-failing-to-qualify-as-a-struct-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!