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 |