【问题标题】:Dynamic instance of c# list with inherited type具有继承类型的 c# 列表的动态实例
【发布时间】:2015-02-19 15:25:22
【问题描述】:

案例 1: 我有以下情况:我想将动态多态性应用于列表。

我有一个基类 ALayer

public class ALayer {
   int Id {get; set;}
}

还有一个包含层列表的基类 A

public class A {
   List<ALayer> Layers {get; set;}
}

然后我将有几个从我的基类扩展而来的类:

public class BLayer: Alayer {
   int blayerattr {get; set;}
}

public class B:A {
   //I want to apply the polymorphism in the constructor
   public B(){
     this.Layers = new List<BLayer>();//error
   }
}

public class CLayer: Alayer {
   int clayerattr {get; set;}
}

public class C:A {
   //I want to apply the polymorphism in the constructor
   public C(){
      this.Layers = new List<CLayer>();//error
   }

}

但编译器给了我一个错误,即无法将子层隐式转换为父层。子层完全不同,所以我决定创建 ALayer 父类。

可以编码吗?还是我的设计有缺陷?或者我如何根据类的类型来实例化我的列表?

提前谢谢你!

已编辑的问题

案例 2: 在最后一种情况下,如何将此泛型应用于继承中的中间类?假设在 A 和 B 之间存在一个中间类

public class Middle:A{
   int   anyatrr;
}

然后我的类 B 继承自 Middle,但仍然在 B 构造函数中是我要应用动态多态性的地方。

public class B:Middle {       
   public B(){
     this.Layers = new List<BLayer>();
   }
}

如何在中间类中结合泛型符号加上从类 A 的继承

【问题讨论】:

  • 是我还是你对你的“B”和“C”的东西做同样的事情。然后,为了让您的问题更清楚,您应该删除“C”案例。

标签: c# list inheritance dynamic polymorphism


【解决方案1】:

您可以使用泛型:

public abstract class ALayer
{
    int Id { get; set; }
}

public abstract class A<T> where T : ALayer
{
    protected List<T> Layers { get; set; }
}

public class B : A<BLayer>
{
    //I want to apply the polymorphism in the constructor
    public B()
    {
        this.Layers = new List<BLayer>();
    }
}

public class BLayer : ALayer
{
    int blayerattr { get; set; }
}

您可以在此处获得有关 C# 泛型的更多信息:https://msdn.microsoft.com/en-us/library/512aeb7t.aspx

更新

案例 2 (归功于 X.L.Ant)

只要做:

public class Middle<T> : A<T>{ and then public class B : Middle<BLayer> { 

【讨论】:

  • 答案是正确的。如果您稍微解释一下泛型不变性,将会更有帮助。
  • 也可以加class A : A&lt;ALayer&gt;:o)
  • 这里讲了一点invariance and covariance
  • 只需:public class Middle&lt;T&gt; : A&lt;T&gt;{ 然后public class B : Middle&lt;BLayer&gt; {
  • 这越来越令人困惑了。请编辑您的问题,或者更好的是,接受@EduardoBrites 的回答并提出一个新问题。 cmets 不适合那样做。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-11
  • 1970-01-01
  • 1970-01-01
  • 2020-06-14
相关资源
最近更新 更多