接口的通用类型约束?

接口的通用类型约束?

问题描述:

我可以这样做:

void MyMethod<T>() where T : class { }

有这样的东西吗?

void MyMethod<T>() where T : interface { }

我不希望明确指定接口名称.

I'd prefer not to specify the interface name explicitly.

另一种选择是,我可以传入受class约束的参数,并在typeof(T).IsInterface返回false时引发异常,但这并不像约束那样干净.

The alternative is that I can pass in an argument that's constrained by class and throw an exception if typeof(T).IsInterface returns false, but that's not as clean as a constraint.

这没有任何意义,因为它不会导致任何限制.

This makes no sense since it doesn't leads to any limitations.

约束class表示类型参数必须是引用类型.

Constraint class means that the type argument must be a reference type.

那么没有显式接口名称的interface应该限制什么呢?

So what interface without explicit interface name should limit?

接口本身只是方法/属性的声明,因此约束条件某物是接口"的字面意思是某物具有某些声明",这是没有用的.

Interface itself is just a declaration of methods/properties, so constraint "something is interface" literally mean "something has some declarations" - that is useless.