What are Virtual Methods?

前端 未结 14 612
傲寒
傲寒 2020-11-29 03:02

Why would you declare a method as \"virtual\".

What is the benefit in using virtual?

14条回答
  •  青春惊慌失措
    2020-11-29 03:34

    In C#, for overriding the base class method in derived class, you have to declare base class method as virtual and derived class method as override as shown below:

    using System;
    namespace Polymorphism
    {
     class A
     {
     public virtual void Test() { Console.WriteLine("A::Test()"); }
     }
    
     class B : A
     {
     public override void Test() { Console.WriteLine("B::Test()"); }
     }
    
     class C : B
     {
     public override void Test() { Console.WriteLine("C::Test()"); }
     }
    
     class Program
     {
     static void Main(string[] args)
     {
    
     A a = new A();
     B b = new B();
     C c = new C();
     a.Test(); // output --> "A::Test()"
     b.Test(); // output --> "B::Test()"
     c.Test(); // output --> "C::Test()"
    
     a = new B();
     a.Test(); // output --> "B::Test()"
    
     b = new C();
     b.Test(); // output --> "C::Test()"
    
     Console.ReadKey();
     }
     }
    }
    

    You can also mix the method hiding and method overriding by using virtual and new keyword since the method of a derived class can be virtual and new at the same time. This is required when you want to further override the derived class method into next level as I am overriding Class B, Test() method in Class C as shown below:

    using System;
    namespace Polymorphism
    {
     class A
     {
     public void Test() { Console.WriteLine("A::Test()"); }
     }
    
     class B : A
     {
     public new virtual void Test() { Console.WriteLine("B::Test()"); }
     }
    
     class C : B
     {
     public override void Test() { Console.WriteLine("C::Test()"); }
     }
    
     class Program
     {
     static void Main(string[] args)
     {
    
     A a = new A();
     B b = new B();
     C c = new C();
    
     a.Test(); // output --> "A::Test()"
     b.Test(); // output --> "B::Test()"
     c.Test(); // output --> "C::Test()"
    
     a = new B();
     a.Test(); // output --> "A::Test()"
    
     b = new C();
     b.Test(); // output --> "C::Test()"
    
     Console.ReadKey();
     }
     }
    }
    

    GOLDEN WORDS: The virtual keyword is used to modify a method, property, indexer, or event declared in the base class and allow it to be overridden in the derived class.

    The override keyword is used to extend or modify a virtual/abstract method, property, indexer, or event of base class into derived class.

    The new keyword is used to hide a method, property, indexer, or event of base class into derived class.

    ENJOY :-)

提交回复
热议问题