C# 将从受约束泛型基类继承的类指定给具有受约束泛型基类的继承基类

C# 将从受约束泛型基类继承的类指定给具有受约束泛型基类的继承基类,c#,class,oop,generics,inheritance,C#,Class,Oop,Generics,Inheritance,我有一个基本类: public abstract class Foo<T> where T : TBase { ... } 我创建了实现此功能的新类: public class Bar1 : Foo<ImplementsTBase1> { ... } public class Bar2 : Foo<ImplementsTBase2> { ... } 公共类Bar1:Foo{…} 公共类Bar2:Foo{…} 现在我想将这些类的两个实例添加到一个容器中,如

我有一个基本类:

public abstract class Foo<T> where T : TBase { ... }
我创建了实现此功能的新类:

public class Bar1 : Foo<ImplementsTBase1> { ... }
public class Bar2 : Foo<ImplementsTBase2> { ... }
公共类Bar1:Foo{…}
公共类Bar2:Foo{…}
现在我想将这些类的两个实例添加到一个容器中,如下所示:

public static List<Foo<TBase>> FooList = new List<Foo<TBase>>();
...
FooList.Add(new Bar1());
FooList.Add(new Bar2());
publicstaticlist=newlist();
...
添加(新的Bar1());
添加(新的Bar2());

但是,我不能这样做。如果您定义了一个将
T
定义为

具有逆变类型参数的接口允许其方法接受派生类型少于接口类型参数指定的派生类型的参数

效果很好

当然,这将限制
IFoo
可以实现的方法

public static List<Foo<TBase>> FooList = new List<Foo<TBase>>();
...
FooList.Add(new Bar1());
FooList.Add(new Bar2());
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());