. Virtual Functions in net

Source: Internet
Author: User

Object-oriented programming has three main elements, encapsulation, inheritance and polymorphism. Virtual functions are an important part of polymorphism, and there are many changes in the inheritance relationship of classes. This article discusses. NET in the support of virtual functions.

First, let's look at the common use of virtual functions in one example:

class CA {
    public virtual void Foo() {
      Console.WriteLine("CA.Foo");
    }
  }

  class CB : CA {
    public override void Foo() {
      Console.WriteLine("CB.Foo");
    }
}

class Test {
    public static void InvokeFoo(CA ca)  {
      ca.Foo();
    }
    public static void Main()  {
      InvokeFoo(new CB());
    }
}

Output results

Cb. Foo

In this example, the CB is converted to a CA while the Invokefoo () is invoked, but when the CA is executed. Foo's time, still called CB Foo. Because the CA is pointing to a CB-type object at this point. This invocation pattern, which we call run-time binding. Because when compiling invokefoo, the compiler cannot get the true type of the parameter CA, and only when it is running can you decide which function to call based on the true type of the CA.

In this example, two keywords are worth our attention, first is virtual, and he tells the compiler that the current function requires run-time binding. Next is override, who tells the compiler that I want to overwrite Foo () in the base class.

Here, perhaps the reader will have doubts about two questions:

[Question]: What about the results without virtual?

[Question]: What's the result without override?

The reader may wish to modify the above example, try the different combinations of these two keywords to see how the output results. Here, I only give the combination condition and its output result.

no
" ">" "" "Style=" "" "", "" "The base class (CA) has VI Rtual " "" "" "" Override < td> style= border:0;padding:0 ""
1 is is the CB. Foo
2 Yes ca. Foo
is Compile error
4 no ca. Foo

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.