代码之家  ›  专栏  ›  技术社区  ›  T.Todua Laurent W.

我可以在基“virtual”方法[duplicate]的父类和父级类中激发“override”方法吗

  •  -1
  • T.Todua Laurent W.  · 技术社区  · 7 年前

    i、 我有两步继承类,并且只有访问权限 Parent_1 班级:

    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; } 
    }
    

    除此之外,我没有权限访问任何代码 父级\u 1 . 我想,什么时候 Parent_2 hello 父级\u 1 你好 他也被解雇了。

    我想应该有办法的,所以什么时候 家长2 执行时,不知何故我在 ,这不可能吗?我知道 xyz 是“改变”了吗,所以可能是“财产改变观察者”?

    2 回复  |  直到 7 年前
        1
  •  0
  •   halfer Jatin Pandey    4 年前

    更新

    不幸的是,这对我没有帮助,因为我既不能控制 代码的其他部分,无论是main()还是执行。。。我只是 为现有应用程序编写模块,该应用程序仅使用我的父应用程序作为

    你做不到,也没有办法做到这一点,我知道(即使是反思), 多态性 base

    原件

    如果我理解您所描述的内容,重写不会触发基方法,除非您显式地告诉它这样做。

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

    额外资源

    Polymorphism (C# Programming Guide)

    类可以重写它们,这意味着它们提供自己的 CLR查找对象的运行时类型,然后 调用虚拟方法的重写。因此在源代码中 可以对基类调用方法,并导致派生类的 要执行的方法的版本

    base (C# Reference)

    base关键字用于从访问基类的成员

    • 对已被另一个方法重写的基类调用方法。

    • 指定在创建派生类的实例时应调用哪个基类构造函数。


    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

        2
  •  0
  •   Rahul    7 年前

    base 关键字

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