我需要指定Generic类型只应在闭合类型中接受枚举类型.如果约束不起作用,有人可以建议一种方法吗?
您不能直接在C#中执行此操作 - 枚举类型不能用作约束.一个选项(grungy)是使用类型初始化器(静态构造函数)在运行时进行检查.它会在运行时使用不合适的类型停止它,但不会在编译时停止.
class Foo<T> where T : struct {
static Foo() {
if (!typeof(T).IsEnum) {
throw new InvalidOperationException("Can only use enums");
}
}
public static void Bar() { }
}
enum MyEnum { A, B, C }
static void Main() {
Foo<MyEnum>.Bar(); // fine
Foo<int>.Bar(); // error
}
Run Code Online (Sandbox Code Playgroud)