如果我有一个带有 struct
约束的通用接口(interface),如下所示:
public interface IStruct<T> where T : struct { }
我可以像这样提供一个枚举作为我的类型 T
,因为 enum
满足 struct
约束:
public class EnumIsAStruct : IStruct<DateTimeKind> { }
C# 7.3 添加了一个 Enum
constraint .以下代码以前是非法的,现在可以编译:
public class MCVE<T> : IStruct<T> where T : struct, Enum { }
然而,令我惊讶的是,以下代码无法编译:
public class MCVE<T> : IStruct<T> where T : Enum { }
...有错误
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
。我的期望错了吗?
最佳答案
This issue是奇怪的(可以说),但预期的行为。
类 System.Enum
本身 可以作为 T
的类型提供。作为类,System.Enum
当然不是 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 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
。
关于c# - 为什么受 'Enum' 约束的泛型类型在 C# 7.3 中不符合 'struct' 的条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50294032/