将通用类型参数限制为System.Enum [英] Restricting the generic type parameter to System.Enum
问题描述
我有一个泛型类型,应该使用枚举
类型指定(实际上,它是几个指定的枚举之一,但我会为 System.Enum
)。
I have a generic type that should be specified with an Enum
type (actually, it's one of several specified enums, but I'll settle for System.Enum
).
当然,编译器可以按以下代码:
Of course the compiler balks at code like:
class Generic<T> where T : Enum {}
与约束不能是特殊类System.Enum '异常。
迄今为止我唯一可以找到的解决方案是使用静态类型初始化器来检查类型参数并抛出例如,如果它不是,实际上是一个枚举,像这样:
The only solution I've been able to come up so far is using the static type initializer to inspect the type parameter and throw an exception if it is not, in fact, an Enum, like this:
class Generic<T>
{
static Generic()
{
if (typeof(T).BaseType != typeof(Enum))
throw new Exception("Invalid Generic Argument");
}
}
至少给我运行时安全,与非枚举参数一起使用。然而,这感觉有点黑客,那么有一个更好的方法来完成这个,理想情况下是编译时的结构?
which at least gives me runtime security that it wont we used with a non-enum parameter. However this feels a bit hacky, so is there a better way to accomplish this, ideally with a compile-time construct?
推荐答案
您可以使用 John Skeets 无约束旋律项目。
使用无约束旋律您将会写:
Using Unconstrained Melody you would write:
class Generic<T> where T : IEnumConstraint
哪些会完成同样的事情。
Which would accomplish the same thing.
这篇关于将通用类型参数限制为System.Enum的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!