这是我的链:
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/