我需要指定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
}
