virtual method of C #

Source: Internet
Author: User

When a method declaration in a class is preceded by a virtual modifier, we call it a virtual method, whereas the other is non-virtual. No more static,abstract, or override modifiers, are allowed after using the virtual modifier.

For a non-virtual method, the method is executed regardless of whether it is invoked by an instance of its class or by an instance of the derived class of the class. For a virtual method, its execution can be changed by the derived class, which is implemented by the overload of the method.

The following example illustrates the difference between a virtual method and a Non-virtual method.

Program Listing 14-3:

Using System;
Class A
{public
 void F () {Console.WriteLine ("A.F");}
 public virtual void G () {Console.WriteLine ("A.G");
}
Class b:a
{
 new public void F () {Console.WriteLine ("B.f");}
 public override void G () {Console.WriteLine ("B.G");}
Class Tese
{
 static void Main () {
    B b=new b ();
    A a=b;
    A.F ();
    B.f ();
    A.G ();
    B.G ();
 }

In the example, Class A provides two methods: Non-virtual F and Virtual method G. Class B provides a new Non-virtual method F, which overrides the inherited F; Class B also overloads the inherited method G. Then the output should be:

A.f
B.f
B.g
B.g

Notice in this example that method A. G () actually calls the B.G, not the A.G. This is because the compile value is a, but the Run-time value is B, so B completes the actual call to the method.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.