且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在C#中使用枚举作为通用类型参数

更新时间:2022-11-21 16:29:20

不,这是不可能的不幸。***的是使用其中T:struct,IComparable,IConvertible,IFormattable (当然不一样)。接口限制来源于实施 系统。枚举

No, it's not possible unfortunately. The best you can do is use where T : struct, IComparable, IConvertible, IFormattable (which of course is not the same). The interface restrictions are derived from the implementation of System.Enum.

除此之外,您可以检查 typeof(T).IsEnum ,它可以在运行时检测问题,大概会抛出异常。但在编译时无法强制执行此限制。

Apart from that, you can check if typeof(T).IsEnum, which can detect the problem at runtime and presumably throw an exception. But there is no way to enforce this restriction at compile time.