3

这是我的链:

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)我在问题中写的实际上是什么。

4

2 回答 2

1

In C# there is no way to do what you're asking for. Essentially you can only call the constructors of the the class you directly inherit from.

If you have control over the implementation of Item then I think the best work around would be to use a virtual Clone/Copy method instead of a copy constructor, that way you can override that method even if MiscItem and OtherItem don't provide their own implementations.

于 2013-07-31T11:36:06.060 回答
1

这行得通。

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);
于 2013-07-31T11:37:40.997 回答