virtual methods

后端 未结 3 398
天命终不由人
天命终不由人 2021-01-28 12:01

If I have a class named \"Parent\" for example. he has a method named \"Print\". the class \"Kid\" is derived, it has a method named

相关标签:
3条回答
  • 2021-01-28 12:44

    You are not overriding the method in your inheriting class - you are shadowing it.

    Instead of:

    public new void Print();
    

    Use:

    public override void Print();
    
    0 讨论(0)
  • 2021-01-28 12:52

    A virtual method call uses the actual type of the object to determine which method to call, while a non-virtual method uses the type of the reference.

    Say that you have:

    public class Parent {
      public void NonVirtualPrint() {}
      public virtual void VirtualPrint() {}
    }
    
    public class Kid : Parent {
      public new void NonVirtualPrint() {}
      override public void VirtualPrint() {}
    }
    

    Then:

    Parent p = new Parent();
    Parent x = new Kid();
    Kid k = new Kid();
    
    p.NonVirtualPrint(); // calls the method in Parent
    p.VirtualPrint(); // calls the method in Parent
    
    x.NonVirtualPrint(); // calls the method in Parent
    x.VirtualPrint(); // calls the method in Kid
    
    k.NonVirtualPrint(); // calls the method in Kid
    k.VirtualPrint(); // calls the method in Kid
    
    0 讨论(0)
  • 2021-01-28 12:56

    When you use the new keyword with a method having same signature as that of a method in parent, it shadows the parent method. Shadowing is different from overriding. Shadowing means your new method will be called if both instance and variable are of type child. Whereas overriding ensures that your overriden method will be called no matter variable is of type child or parent.

    Edit:

    Take a look at the comparison sheet on MSDN.

    0 讨论(0)
提交回复
热议问题