Virtual functions

后端 未结 7 1541
清酒与你
清酒与你 2020-12-11 06:39

I don\'t really understand - when am I supposed to use virtual functions?I\'ll be glad if someone could explain it to me, thanks.

7条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-11 07:32

    probably easiest to understand through an example So imagin we have code like below

    class Base{
    public virtual string VirtualMethod(){
        return "base virtual";
    }
    
    public string NotVirtual(){
        return "base non virtual";
    }
    }
    
    class Derived : Base{
      public override string VirtualMethod(){
            return "Derived overriden";
      }
      public new string NotVirtual(){
            return "new method defined in derived";
      }
    }
    
    }
    

    if you use the code as below

      Base b = new Base();
      Derived d = new Derived();
      Base b2 = d;
    
      Console.WriteLine(b.VirtualMethod());
      Console.WriteLine(d.VirtualMethod());
      Console.WriteLine(b2.VirtualMethod());
    
      Console.WriteLine(b.NotVirtual());
      Console.WriteLine(d.NotVirtual());
      Console.WriteLine(b2.NotVirtual());
    

    It's worth paying attention to that b2 a d is the exact same object!

    the result of the above would be:

    base virtual

    Derived overriden

    Derived overriden

    base non virtual

    new method defined in derived

    base non virtual

    Eventhough the last two lines call a method name NotVirtual on the same object. Because te variables are declared of Base and Derived and the method is not virtual the declared type of the variable determine the method called whereas if the method is virtual the runtime type of the object is the determining factor for which method that will be called

提交回复
热议问题