C# - calling base version of overridden method

Maras :

Suppose there is base class A and derived class B.

Class A has two functions: fun1() and fun2(), where fun1() calls fun2().

Class B overrides fun1() and fun2(), and again fun1() calls fun2().

However, I'd like to call base.fun1() in overriden fun2(). Since base.fun1() calls fun2() instead of the base class' version that creates quite unfortunate loop:

fun1() -> fun2() -> base.fun1() -> fun2() -> base.fun1() -> ...

Is there any way to force base.fun1() to call base version of fun2()? I am aware that the real problem probably lies in bad design of those classes, but I'm still curious if it's somehow possible.

jasonvuriker :

Use method hiding.

Method hiding is also known as shadowing. The method of the parent class is available to the child class without using the override keyword in shadowing. The child class has its own version of the same function. Use the new keyword to perform shadowing.

public class A
{
    public virtual void Func1() { Func2(); }

    public virtual void Func2() { Console.WriteLine("A: Func2"); }
}

public class B : A
{
    public override void Func1() { Func2(); }

    public new void Func2() { base.Func1(); }
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=375701&siteId=1