Home >Backend Development >C++ >How to Call a Base Class's Base Class Method in C#?
Calling base.base.method():
In object-oriented programming, it's common practice to create class hierarchies with base and derived classes. When overriding a method in the derived class, you can invoke the base class implementation using base. However, in certain scenarios, you may encounter a situation where you want to access the base class of the base class.
Consider the following example code:
class Base { public virtual void Say() { Console.WriteLine("Called from Base."); } } class Derived : Base { public override void Say() { Console.WriteLine("Called from Derived."); base.Say(); } } class SpecialDerived : Derived { public override void Say() { Console.WriteLine("Called from Special Derived."); base.Say(); } }
When you call sd.Say() for an instance of SpecialDerived, you expect the following output:
Called from Special Derived. Called from Derived. Called from Base.
However, you actually get:
Called from Special Derived. Called from Derived. /* this is not expected */ Called from Base.
The unexpected call to Derived.Say() is because base always refers to the immediate base class in the hierarchy. Therefore, SpecialDerived.Say() invokes Derived.Say() before calling Base.Say().
To avoid this behavior, you can't directly use base.base.method(). Instead, you can utilize the following approach:
class Derived : Base { public override void Say() { CustomSay(); base.Say(); } protected virtual void CustomSay() { Console.WriteLine("Called from Derived."); } } class SpecialDerived : Derived { protected override void CustomSay() { Console.WriteLine("Called from Special Derived."); } }
By introducing the intermediate method CustomSay(), you have control over what's executed in the derived class call chain. In this case, SpecialDerived overrides CustomSay() to provide its own behavior, effectively skipping Derived.CustomSay().
Alternatively, you can access the base class method handle using reflection and invoke it directly, as shown below:
class SpecialDerived : Derived { public override void Say() { Console.WriteLine("Called from Special Derived."); var ptr = typeof(Base).GetMethod("Say").MethodHandle.GetFunctionPointer(); var baseSay = (Action)Activator.CreateInstance(typeof(Action), this, ptr); baseSay(); } }
The above is the detailed content of How to Call a Base Class's Base Class Method in C#?. For more information, please follow other related articles on the PHP Chinese website!