自动调用基本方法 [英] Automatically call base method
本文介绍了自动调用基本方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要在调用override一个时自动调用基类方法(比如构造函数调用base)。例如:
I need to call automatically base class method when calling overriden one (like constructors call base). For example:
class A
{
public void Fun()
{
Console.Write("Class A!");
}
}
class B : A
{
public void Fun()
{
Console.Write("Class B!");
}
}
我想在屏幕上看到
A类!执行下一个代码时,B级!
Class A! Class B!
:
B b = new B();
b.Fun();
有谁能告诉我需要更改示例代码或更好地编写以获得所需结果?谢谢。
Could anyone tell me please what need to change in example code or how better to write to get required result? Thanks.
推荐答案
如果您不想明确调用它,请确保 A.Fun( )
在派生类中调用,您可以使用名为模板方法模式:
If you don't want to call it explicitly and therefore ensure A.Fun()
is called in the derived class, you could use something called the template method pattern:
class A
{
public void Fun()
{
Console.Write("Class A!");
FunProtected();
}
protected virtual void FunProtected()
{
}
}
class B : A
{
protected override void FunProtected()
{
Console.Write("Class B!");
}
}
这会给你:
new A().Fun() -> "Class A!"
new B().Fun() -> "Class A! Class B!"
这篇关于自动调用基本方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文