开发者

Automatically call base method

开发者 https://www.devze.com 2023-01-23 17:48 出处:网络
I need to call automatically base class method when calling overriden one (like constructors call base). For example:

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!");
    }
}

I want to see on the screen

Class A! Class B!

when executing next code:

B b = new B();
b.Fun();

Could anyone tell me please what need to chan开发者_如何学Cge in example code or how better to write to get required result? Thanks.


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!");
    }
}

This would give you:

new A().Fun() -> "Class A!"
new B().Fun() -> "Class A! Class B!"


If you want such behavior you will need to change platform/language. .NET doesn't automatically call the base method. You need to call it explicitly. Also your method needs to be virtual or you will be hiding it in the derived class:

class A
{
    public virtual void Fun()
    {
        Console.Write("Class A!");
    }
}

class B : A
{
    public override void Fun()
    {
        // call the base method which will print Class A!
        base.Fun(); 
        Console.Write("Class B!");
    }
}

Now when you do this:

B b = new B();
b.Fun();

you will get the required result.


Can still be so:

interface IFun
{
    void Fun();
}

abstract class A : IFun
{
    void IFun.Fun()
    {
        Console.Write("Class A!");
        Fun();
    }
    protected abstract void Fun();
}

class B : A
{
    protected override void Fun()
    {
        Console.Write("Class B!");
    }
}

IFun b = new B();
b.Fun();

This works if object reference is IFun.


Just for reference, you could use a wrapper pattern that puts an A inside a B. Here is a crude example!

interface IFunClass {
    void Fun();
}

class A : IFunClass {
    public void IFunClass.Fun() {
        Console.Write("Class A!");
    }
}

class B : IFunClass {
    public B(IFunClass f) {
        this.m_SomethingFun = f;
    }

    public void IFunClass.Fun() {

        this.m_SomethingFun.Fun();

        Console.Write("Class B!");
    }

    private IFunClass m_SomethingFun;
}

A a = new A();
B b = new B(a);

b.Fun() // will call a.Fun() first inside b.Fun()
0

精彩评论

暂无评论...
验证码 换一张
取 消