usingSystem;classtest{ Public classA { Public Virtual voidFUN1 (inti) {Console.WriteLine (i); } Public voidFun2 (A A) {A.fun1 (3); FUN1 (7); } } Public classb:a { Public Override voidFUN1 (inti) {Console.WriteLine (i+1); } } Public Static voidMain () {A A=NewA (); b b=NewB (); A.fun2 (b); B.fun2 (a); }}
In the above program, Class B inherits from Class A, and in the main () function, each of these two class instance variables, a, b
A.fun2 (b);
is performed as follows:
1. Object A first calls the Fun2 method of Class A, fun2 (a) requires an instance variable of type A, and here the
The actual parameter is an instance variable B of type B. So this will implicitly convert B into a type, the conversion process,
B will lose its own unique features.
2. Implementation of B.FUN1 (3), B's Fun1 method covers the Fun1 method of Class A, so the actual implementation of Class B FUN1
method, print out 4 (i+1).
3. Execute FUN1 (7), where the calling object is not specified, and the current calling object is assumed to be the default. Current is a in call, then execute
A.FUN1 (7), A is an instance variable of Class A, the fun1 of Class A is executed, and 7 (i) is printed.
B.fun2 (a);
is performed as follows:
1. Because there is no Fun2 method in Class B, the Fun2 method of its parent class A is executed, where the actual argument is an instance of type a
Variable A, so no conversion is required.
2. Perform a.fun1 (3) and print out 3 (i).
3. Execute FUN1 (7), i.e. B.FUN1 (7), print out 8 (i+1).
The final output of the program should be:
4
7
3
8
Small example Analysis C # inheritance mechanism