Calling base.base.method()
In this code, we have a class hierarchy where SpecialDerived inherits from Derived, which in turn inherits from Base. Each class has an overridden Say() method that prints a message indicating which class it was called from.
When sd.Say() is called in the Main() method, we expect the following output:
Called from Special Derived. Called from Derived. Called from Base.
However, the actual output includes an unexpected call to Derived.Say().
To prevent this, we can modify the SpecialDerived class to use the CustomSay() method instead of overriding Say(). This way, only the CustomSay() method is called when sd.Say() is invoked:
class SpecialDerived : Derived { protected override void CustomSay() { Console.WriteLine("Called from Special Derived."); } }
Another alternative, discussed in a separate answer, is to access the Say() method of Base directly using reflection:
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(); } }
While this approach is technically possible, it is not recommended as it is considered bad practice.
The above is the detailed content of Why Does Calling `base.base.method()` Produce Unexpected Results in C# Inheritance, and How Can It Be Avoided?. For more information, please follow other related articles on the PHP Chinese website!