c# - 我可以为长继承链中的子类调用最顶层的构造函数吗?

标签 c# inheritance constructor

这是我的链:

public abstract class Item ->
  public abstract class MiscItem ->
    public abstract class OtherItem ->
       public class TransformableOther;

Item中,有一个拷贝构造函数:

public Item (Item other)
{
 // copy stuff ...
}

我想这样做:

var trans = new TransformableOther (otherItem);

当然那是行不通的,我去了 TransformableOther 并尝试了:

public TransformableOther(Item other): base (other) {}

但这并没有奏效,当然那只是调用直接在上面的父级。我去了那里,到 OtherItem 并做了同样的事情,所以对于它的父 MiscItem, 它没有用。

我怎样才能达到我想要的? - 如果我做不到,那么解决这个问题的技巧是什么?

谢谢。

编辑:不好的是,出于某种原因,我在代码中执行的是 base.Item(otherItem) 而不是 base(otherItem) 这实际上是我在问题。

最佳答案

这有效。

public abstract class Item
{
    private Item other;
    public Item(Item item)
    {
        System.Diagnostics.Debug.WriteLine("Creating Item!");
        other = item;
    }

    public abstract class MiscItem : Item
    {
        public MiscItem(Item item) : base(item)
        {

        }

        public abstract class OtherItem : MiscItem
        {
            public OtherItem(Item item) : base(item)
            {

            }

            public class TransformableOther : OtherItem
            {
                public TransformableOther() : base(null)
                {

                }

                public TransformableOther(Item item) : base(item)
                {

                }

            }
        }
    }
}

然后你可以用

测试它
         Item.MiscItem.OtherItem.TransformableOther other = new Item.MiscItem.OtherItem.TransformableOther();
        var item = new Item.MiscItem.OtherItem.TransformableOther(other);

关于c# - 我可以为长继承链中的子类调用最顶层的构造函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17969005/

相关文章:

c++ - C++派生类是否必须在头文件中包含继承函数/成员的定义?

java - 具有公共(public)构造函数而不是 protected 构造函数的抽象类有什么意义吗?

c++ - 构造函数 : init() method, 指针中的异常,大型 try/catch 或..?

c# - 将 Sphero 2.0 连接到 Mac OSX 10.9

python - 在类中调用父类的 __call__ 方法

C# 过滤器列表删除任何双对象

c++ - C++中调用基类模板构造函数

c++ - 具有类值的 map 的构造函数

c# - 将 Linq 表达式输出转储到控制台。

c# - 文本框空验证