为什么在“ C#7.3”中不能由“枚举”限定的通用类型? [英] Why is a generic type constrained by 'Enum' failing to qualify as a 'struct' in C# 7.3?
问题描述
如果我的通用接口具有 struct
约束,例如:
If I have a generic interface with a struct
constraint like this:
public interface IStruct<T> where T : struct { }
我可以提供枚举作为我的类型 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添加了 枚举
约束。以前是非法的以下代码现在可以编译:
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 { }
...有错误
CS0453类型 T必须是不可为空的值类型,以便在通用类型或方法 IStruct中将
用作参数 T
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'
为什么?我希望受 Enum
约束的泛型可用作类型参数,而该类型受 struct
约束,但是似乎并非如此-我必须将 Enum
约束更改为 struct Enum
。我的期望不对吗?
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?
推荐答案
此问题很奇怪(可以说),但是是预期的行为。
This issue is strange (arguably), but expected, behavior.
类 System.Enum
本身可以作为 T
的类型提供。作为类, System.Enum
当然不是 struct
!
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> { }
CLR本身。
System.Enum
是一个类,但是
每个从System.Enum
派生的类型都是struct
。因此,对System.Enum
的约束
本身并不意味着struct
,因为您可以传递
System.Enum
作为通用类型参数...
This is an odd behavior by the CLR itself.
System.Enum
is a class, but every type that derives fromSystem.Enum
is astruct
. So a constraint onSystem.Enum
by itself doesn't implystruct
since you could passSystem.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.
解决方案是当您希望将具体类型约束为 struct,Enum
时,将其作为您的标准做法任何特定的枚举。如果另外您希望接受 System.Enum
类作为您的通用类型,则只有这样,您才限于 Enum
。
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
.
这篇关于为什么在“ C#7.3”中不能由“枚举”限定的通用类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!