调用base.base.method():
在面向对象编程中,使用基类和派生类创建类层次结构是常见的做法类。当重写派生类中的方法时,可以使用 base 调用基类实现。但是,在某些场景下,您可能会遇到想要访问基类的基类的情况。
考虑以下示例代码:
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(); } }
当您调用 sd. Say() 对于 SpecialDerived 的实例,您期望得到以下输出:
Called from Special Derived. Called from Derived. Called from Base.
但是,您实际上get:
Called from Special Derived. Called from Derived. /* this is not expected */ Called from Base.
对 Derived.Say() 的意外调用是因为 base 始终引用层次结构中的直接基类。因此,SpecialDerived.Say() 在调用 Base.Say() 之前调用 Derived.Say()。
为了避免这种行为,不能直接使用 base.base.method()。相反,您可以使用以下方法:
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."); } }
通过引入中间方法 CustomSay(),您可以控制派生类调用链中执行的内容。在这种情况下,SpecialDerived 重写 CustomSay() 以提供自己的行为,有效地跳过 Derived.CustomSay()。
或者,您可以使用反射访问基类方法句柄并直接调用它,如下所示:
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(); } }
以上是如何在C#中调用基类的基类方法?的详细内容。更多信息请关注PHP中文网其他相关文章!