Home > Backend Development > C++ > Why Does Calling `base.base.method()` Produce Unexpected Results in C# Inheritance, and How Can It Be Avoided?

Why Does Calling `base.base.method()` Produce Unexpected Results in C# Inheritance, and How Can It Be Avoided?

Mary-Kate Olsen
Release: 2024-12-28 04:38:09
Original
660 people have browsed it

Why Does Calling `base.base.method()` Produce Unexpected Results in C# Inheritance, and How Can It Be Avoided?

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.
Copy after login

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.");
    }
}
Copy after login

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();
    }
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template