简体   繁体   中英

calling parent methods from overriden class in C#

I have the following code:

class ClassA
{
    public virtual void DoSomething()
    {
        DoSomething(1); // when called from ClassB, it calls DoSomething from ClassA with an infinite recursion
    }

    public virtual void DoSomething(int someInt)
    {
        // do something
    }
}

class ClassB : ClassA
{
    public override void DoSomething()
    {
        DoSomething(1);
    }
    public override void DoSomething(int someInt)
    {
         base.DoSomething(someInt);

        // do something
    }
}

class Program
{
    void someMethod()
    {
        ClassB instance = new ClassB();
        instance.DoSomething(); // stack overflow caused by infinite recursion
    }
}

My problem is that when I call ClassB.DoSomething(); and it calls base.DoSomething(someInt); I want the parent class which ClassB is derived to call ClassA's method instead of the overriden one.

Is there a way to do this in a clean way without copying/pasting repeated code?

You can modify the base class like so:

class ClassA
{
    public virtual void DoSomething()
    {
        DoSomethingHelper(1); // when called from ClassB, it calls DoSomething from ClassA with an infinite recursion
    }

    public virtual void DoSomething(int someInt)
    {
        DoSomethingHelper(someInt);
    }

    private void DoSomethingHelper(int someInt)
    {
        // do something
    }
}

By refactoring out the entire method into a private method you provide a means to call the current class' definition of the method while still providing a virtual method for the child class to access.

When you override the virtual method you can't call it without the base keyword, so you cannot cal if from that class. You can try using what Jon B said and use method shadowing instead of overriding.

class ClassA
{
    public void DoSomething()
    {
        DoSomething(1); 
    }

    public void DoSomething(int someInt)
    {
        Console.WriteLine("a");
    }
}

class ClassB : ClassA
{
    public new void DoSomething()
    {
        DoSomething(1);
    }

    public new void DoSomething(int someInt)
    {
        base.DoSomething();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM