我可以在基本 "virtual" 方法的父级和祖父级 类 中触发 `override` 方法吗

Can I fire `override` method in parent and grand-parent classes of base "virtual" method

即我有两步继承 class,并且只能访问 Parent_1 class:

public class Base
{
    public virtual void hello (){}
}

//
public class Parent_1 : Base
{
    public override void hello (){ Print("Hi 1"); }
}

public class Parent_2 : Parent_1
{ 
    public override void hello (){ Print("Hi 2");  xyz =123; } 
}

除了 Parent_1,我无权访问任何代码。我想,当 Parent_2hello 被执行时,我的 Parent_1hello 也被解雇了。

我认为应该存在某种方式,所以当执行 Parent_2 时,我在 Parent_1 中以某种方式得到通知(事件处理程序或其他),这不可能吗?我知道 xyz 在那里 "changed",所以也许 "property change observer" ?

那你为什么不能使用 base 关键字

调用基础 class
public class Parent_2 : Parent_1
{         
    public override void hello (){ base.hello(); Print("Hi 2"); }        
}

更新

unfortuantely that doesnt help in my case, because I neither control other parts of code, neither main() like executions... I am just writing a module for existing app, which only uses my Parent_1 as intermediate between Parent_2 and Base

我知道你不能也没有办法做到这一点(即使有反射也不行),C# 中的 多态性 实际上保证了被覆盖的方法将被调用,除非你使用 base

告诉它在重写的方法中这样做

原创

如果我理解您的描述,除非您明确告诉它这样做,否则重写不会触发基本方法。

public class Parent_2 : Parent_1
{ 
    public override void hello ()
    { 
       base.hello();
       Print("Hi 2"); 
    }
}

其他资源

Polymorphism (C# Programming Guide)

Base classes may define and implement virtual methods, and derived classes can override them, which means they provide their own definition and implementation. At run-time, when client code calls the method, the CLR looks up the run-time type of the object, and invokes that override of the virtual method. Thus in your source code you can call a method on a base class, and cause a derived class's version of the method to be executed.

base (C# Reference)

The base keyword is used to access members of the base class from within a derived class:

  • Call a method on the base class that has been overridden by another method.

  • Specify which base-class constructor should be called when creating instances of the derived class.


public class Base
{
    public virtual void hello()
    {
    }
}

//
public class Parent_1 : Base
{
    public override void hello()
    {
        Console.WriteLine("Hi 1");
    }
}

public class Parent_2 : Parent_1
{
    public override void hello()
    {
        base.hello();
        Console.WriteLine("Hi 2");
    }
}

public static void Main()
{
    Parent_1 p = new Parent_2();
    p.hello();
}

输出

Hi 1
Hi 2

Full Demo Here