将从受约束的泛型基类继承的类分配给受约束的泛型的继承基类

时间:2018-06-28 16:32:46

标签: c# class oop generics inheritance

我有一个基类:

public abstract class Foo<T> where T : TBase { ... }

我还有以下实现TBase的类:

public abstract class ImplementsTBase1 : TBase { ... }
public abstract class ImplementsTBase2 : TBase { ... }

我创建实现此目的的新类:

public class Bar1 : Foo<ImplementsTBase1> { ... }
public class Bar2 : Foo<ImplementsTBase2> { ... }

现在我想将这些类的两个实例添加到这样的容器中:

public static List<Foo<TBase>> FooList = new List<Foo<TBase>>();
...
FooList.Add(new Bar1());
FooList.Add(new Bar2());

但是,我不能这样做。我该怎么办?

1 个答案:

答案 0 :(得分:0)

如果您定义一个将T定义为covariant的接口

  

具有相反类型参数的接口允许其方法接受比接口类型参数指定的派生类型更少的参数。

public interface IFoo<out T> where T : TBase{}

然后从中得出:

public abstract class Foo<T> : IFoo<T> where T : TBase{}

现在可以

List<IFoo<TBase>> FooList = new List<IFoo<TBase>>();

FooList.Add(new Bar1());
FooList.Add(new Bar2());

效果很好。

当然,这将限制IFoo<out T>可以实现的方法。