Calling a parent class method from a derived derived class

I have it:

public class Base { public virtual void Connect() { // do stuff } } public class Derived1 : Base { public override void Connect() { base.Connect(); // do other stuff } } public class Derived2 : Derived { public override void Connect() { base.Connect() // Here I want to call Base::Connect(), not Derived::Connect() } } 

Is there any way I can call Base :: Connect from Derived2 because I want to skip the β€œdo other things” part from Derived1 :: Connect ()?

edit: It is imperative that I get Derived1.

+4
source share
2 answers

Yo may try to split Connect into two functions and call DoConnect from all derived classes where necessary:

 public class Base { public virtual void Connect() { DoConnect(); } protected void DoConnect() { // do stuff } } ... public class Derived2 : Derived1 { public override void Connect() { DoConnect(); ... } } 

If you cannot update the base class, you can do this separation on Derived1

 public class Derived1 : Base { public virtual void Connect() { DoConnect(); } protected void DoConnect() { base.Connect(); } } 
+3
source

Dose C # does not provide a direct way to call base.base.method() you need to change your design first.
kindly check this answer why-c-sharp-doesnt-support-base-base

So you need to change your design a bit to do a little trick or workaround.

  • Define a new method in your Derived1 class in which it works, just to call base.Connect()
  • Then, in your Derived2() class, define your Connect() , which will simply call the previous function defined in the previous step.

check this example:

 public class Base { public virtual void Connect() { // do stuff } } public class Derived1: Base { public override void Connect() { base.Connect(); // do other stuff } public void CallBaseConnnect() { //here make only one call to base.Connect(). //that how class Derived1 'll provide you away to call base.Connect(). base.Connect(); } } public class Derived2: Derived { public override void Connect() { //here just make a call to CallBaseConnnect() in base class Derived1 //that 'll equivalent to base.base.Connect. base.CallBaseConnnect(); } } 
+1
source

Source: https://habr.com/ru/post/1487091/


All Articles