我有一个通用类,但我希望我的类型被迫从一个或另一个接口继承。例如:
public class MyGeneric<T> where T : IInterface1, IInterface2 {}
Run Code Online (Sandbox Code Playgroud)
上面的方法将迫使T从IInterface1和IInterface2继承到继承关系,但是我可以强迫T从IInterface1或IInterface2(或两者)继承吗?
定义一个基本接口-它甚至不必具有任何成员,并让Interface1和Interface2都对其进行扩展。然后将范围T设为基本接口类型。仅当您希望从您的接口(而不是框架中的任何现有接口)派生泛型派生时,这才有效。
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>();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1270 次 |
| 最近记录: |