What are Virtual Methods?

2019-01-11 00:15发布

Why would you declare a method as "virtual".

What is the benefit in using virtual?

14条回答
地球回转人心会变
2楼-- · 2019-01-11 01:01

Virtual functions are the functions that doesn't really exists.The derived class can modify the virtual function by overriding it.Virtual functions are one of the way to achieve run time polymorphism

    public class sample {
      public virtual void fun(){
        Console.WriteLine("base sample class \n");
      }
    }
    public class A : sample{
      public override void fun(){
        Console.WriteLine("Class A \n");
      }
    }
    public class B : sample{
      public override void fun(){
        Console.WriteLine("Class B \n");
      }
    }
    class run{
      public static void main(String[] args){
        sample obj = new sample();
        sample obj1 = new A();
        sample obj2 = new B();
        obj.fun();
        obj1.fun();
        obj2.fun();
      }
    }
查看更多
姐就是有狂的资本
3楼-- · 2019-01-11 01:04

Here it is explained clearly with example C# Virtual Method

查看更多
登录 后发表回答