c# - 为什么受 'Enum' 约束的泛型类型在 C# 7.3 中不符合 'struct' 的条件?

标签 c# .net generics enums c#-7.3

如果我有一个带有 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 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.

解决方案是当您希望将具体类型限制为任何特定枚举struct, Enum 作为您的标准做法>。如果另外您希望接受类 System.Enum 作为您的泛型类型,那么您只会限制为 Enum

关于c# - 为什么受 'Enum' 约束的泛型类型在 C# 7.3 中不符合 'struct' 的条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50294032/

相关文章:

c# - 无法在 ASP.Net MVC 5 中找到区域 View

.NET:协方差和逆变

java - 泛型上的通配符错误

java - 接口(interface)中的通用方法返回未检查的强制转换

c# - 被遗弃的互斥异常

c# - 在脚本中发布构建事件#

c# - 在 ASP.Net Core 依赖注入(inject)中删除服务

c# - 在c#中使用USB连接

c# - 从控制台读取 unicode

java - 自动装箱不适用于参数化类型