我有一个泛型类,但我希望我的类型强制从一个或另一个接口(interface)继承。例如:
public class MyGeneric<T> where T : IInterface1, IInterface2 {}
以上将强制 T 从 IInterface1 和 IInterface2 继承,但我可以强制 T 从 IInterface1 或 IInterface2 (或两者)继承吗?
最佳答案
定义一个基本接口(interface)——它甚至不必有任何成员,并让 Interface1 和 Interface2 都扩展它。然后将 T 的范围设为基本接口(interface)类型。仅当您希望从接口(interface)派生通用接口(interface)而不是框架中的任何现有接口(interface)时,这才有效。
public interface BaseInterface
{
}
public interface Interface1 : BaseInterface
{
void SomeMethod();
}
public interface Interface2 : BaseInterface
{
void SomeOtherMethod();
}
public class MyGenericClass<T> where T : BaseInterface
{
...
}
var myClass1 = new MyGenericClass<Interface1>();
var myClass2 = new MyGenericClass<Interface2>();
关于c# - 是否可以强制泛型类从两个接口(interface)之一继承类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/525158/