[英]Using abstract override and calling the base class
Consider the following - 考虑以下 -
void Main()
{
var c = new C();
c.Print();
}
public abstract class A
{
public virtual void Print()
{
Console.WriteLine("I'm in A!");
}
}
public abstract class B : A
{
public abstract override void Print();
}
public class C : B
{
public override void Print()
{
Console.WriteLine("I'm in C!");
base.Print();
}
}
This, of course, won't compile, as it thinks I am trying to invoke B's print method, which is abstract. 当然,这不会编译,因为它认为我正在尝试调用B的抽象打印方法。 What I want to do is call C's print method, and then have it call the base's print method, which would "chain" back to A's print method. 我想做的是调用C的print方法,然后让它调用base的print方法,它将“链接”回A的print方法。 I would like the output to be - 我希望输出是-
I'm in C!
I'm in A!
Is doing this even possible? 这样做有可能吗? What am I doing wrong? 我究竟做错了什么?
EDIT: I'd like to add that the main point about the code above is that I'm trying to force anyone that extends B to implement their own Print method. 编辑:我想补充一点,关于上面的代码的要点是,我试图强迫任何扩展B的人实现自己的Print方法。
Well, you could do 好吧,你可以做
public abstract class A
{
public virtual void Print()
{
Console.WriteLine("I'm in A!");
}
}
public abstract class B : A
{
public override void Print()
{
base.Print();
}
}
public class C : B
{
public override void Print()
{
Console.WriteLine("I'm in C!");
base.Print();
}
}
Which is effectively 哪个有效
public abstract class A
{
public virtual void Print()
{
Console.WriteLine("I'm in A!");
}
}
public abstract class B : A
{
}
public class C : B
{
public override void Print()
{
Console.WriteLine("I'm in C!");
base.Print();
}
}
If you remove the attempt to override from B
: 如果删除从B
覆盖的尝试:
public abstract override void Print();
That is exactly what it will do. 那正是它会做的。
Full Code: 完整代码:
static void Main(string[] args)
{
var c = new C();
c.Print();
Console.ReadLine();
}
public abstract class A
{
public virtual void Print()
{
Console.WriteLine("I'm in A!");
}
}
public abstract class B : A
{
}
public class C : B
{
public override void Print()
{
Console.WriteLine("I'm in C!");
base.Print();
}
}
Result: 结果:
I'm in C!
I'm in A!
There is no way you can force a class to provide it's own implementation, after all it could just call base.Print()
or even just provide an empty method implementation. 您无法强迫类提供其自己的实现,毕竟它只能调用base.Print()
甚至只是提供一个空的方法实现。
For a similar discussion see: How to force overriding a method in a descendant, without having an abstract base class? 对于类似的讨论,请参见: 如何在没有抽象基类的情况下强制在后代中重写方法?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.