【问题标题】:Assigning class that inherits from a constrained generic base class to the inherited base class with the constrained generic将从受约束的泛型基类继承的类分配给具有受约束的泛型的继承基类
【发布时间】:2018-06-28 16:32:46
【问题描述】:

我有一个基类:

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());

但是,我不能这样做。我能做些什么来实现它?

【问题讨论】:

    标签: c# class oop generics inheritance


    【解决方案1】:

    如果你定义一个接口,将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&lt;out T&gt; 可以实现的方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多