可以强制泛型类具有从两个接口之一继承的类型吗?

时间:2021-01-23 18:55:16

I have a generic class, but I want my type to be forced to inherit from either one or the other interface. For example:

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

public class MyGeneric<T> where T : IInterface1, IInterface2 {}

The above will force T to inherti from both IInterface1 and IInterface2 but can I force T to inhert from IInterface1 OR IInterface2 (or both)?

以上将强制T从IInterface1和IInterface2的inherti,但我可以强制T从IInterface1或IInterface2(或两者)的内部?

2 个解决方案

#1


Define a base interface -- it doesn't even have to have any members and let both Interface1 and Interface2 extend it. Then scope T to be of the base interface type. This only works if you want to have the generic derive from your interfaces, not any of the existing ones in the framework.

定义一个基本接口 - 它甚至不需要任何成员,并且让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>();

#2


No, you can't do this. It simply doesn't make sense.

不,你不能这样做。它根本没有意义。

The best you could do would be to create 2 empty subclasses of your generic class, and make the generic class abstract. Like this:

您可以做的最好的事情是创建泛型类的2个空子类,并使泛型类抽象化。像这样:

abstract class MyGenericClass<T>
{
  ...
}

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

public class MyClass2<T> : MyGenericClass<T>, IInterface2
{ }

#1


Define a base interface -- it doesn't even have to have any members and let both Interface1 and Interface2 extend it. Then scope T to be of the base interface type. This only works if you want to have the generic derive from your interfaces, not any of the existing ones in the framework.

定义一个基本接口 - 它甚至不需要任何成员,并且让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>();

#2


No, you can't do this. It simply doesn't make sense.

不,你不能这样做。它根本没有意义。

The best you could do would be to create 2 empty subclasses of your generic class, and make the generic class abstract. Like this:

您可以做的最好的事情是创建泛型类的2个空子类,并使泛型类抽象化。像这样:

abstract class MyGenericClass<T>
{
  ...
}

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

public class MyClass2<T> : MyGenericClass<T>, IInterface2
{ }