C# 是否可以强制泛型类从两个接口之一继承类型?

C# 是否可以强制泛型类从两个接口之一继承类型?,c#,.net,generics,C#,.net,Generics,我有一个泛型类,但我希望强制我的类型从一个或另一个接口继承。例如: public class MyGeneric<T> where T : IInterface1, IInterface2 {} 公共类MyGeneric其中T:IInterface1,IInterface2{} 上述操作将强制T从IIInterface1和IIInterface2输入,但我可以强制T从IIInterface1或IIInterface2(或两者)输入吗?不,您不能这样做。这根本没有道理 最好是创建泛

我有一个泛型类,但我希望强制我的类型从一个或另一个接口继承。例如:

public class MyGeneric<T> where T : IInterface1, IInterface2 {}
公共类MyGeneric其中T:IInterface1,IInterface2{}

上述操作将强制T从IIInterface1和IIInterface2输入,但我可以强制T从IIInterface1或IIInterface2(或两者)输入吗?

不,您不能这样做。这根本没有道理

最好是创建泛型类的2个空子类,并将泛型类抽象化。像这样:

abstract class MyGenericClass<T>
{
  ...
}

public class MyClass1<T> : MyGenericClass<T>, IInterface1
{ }

public class MyClass2<T> : MyGenericClass<T>, IInterface2
{ }
抽象类MyGenericClass
{
...
}
公共类MyClass1:MyGenericClass,IInterface1
{ }
公共类MyClass2:MyGenericClass,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>();
公共接口BaseInterface
{
}
公共接口接口1:基本接口
{
无效方法();
}
公共接口接口2:基本接口
{
void SomeOtherMethod();
}
公共类MyGenericClass,其中T:BaseInterface
{
...
}
var myClass1=新的MyGenericClass();
var myClass2=新的MyGenericClass();

您能举一个您想针对MyGeneric编写的代码示例吗?也许有更好的方式来表达它。你不需要结构性的打字!:)使用泛型约束可以做很多很酷的事情,但是由于.NET类型系统不会直接支持它们,C#可能也不会这样做。