Reading notes (About Virtual and New in C #)

xiaoxiao2021-03-06  35

Your own reading experience, if you feel the pediatrics, please understand a bird

Let's take a picture below:

Using system;

Namespace Test_consoleApplication {Public Class a () {Console.WriteLine ("this is class1'a");}

Public virtual void aa () {console.writeLine ("this is class1'aa);}

}

Public class myclass2: myclass1 {public new void a () {console.writeline ("this is class2'a");}

Public override void aa () {console.writeLine ("this is class2'aa";}}

Public class myclass3 {static void main () {myclass1 c1; myclass2 c2;

C1 = new myclass1 (); c1.a (); c1.aa (); console.writeline (c1.gettype (). Tostring ()); c1 = new myclass2 (); c1.a (); c1.aa (); Console.writeLine (c1.gettype (). TOSTRING ());

C2 = new myclass2 (); c2.a (); c2.aa (); console.writeline (C2.GETTYPE (). TOSTRING ());

Console.readline ();}}

}

The input result is:

The Virtual method is mainly used to rewrite the method in the base class. The New method embodies the version control:

Two aspects:

For example, two methods A () and B () are defined in the base class, and the A () is rewritten in the derived class, and we use the base class to derive class, work normally, HOHO release program. After a month, we must re-expand the derived class and feel the same method to expand B () so that the program gives the compilation prompt. At this time, the version of the body appeared. I originally used the base class to derive class to call the B () method. The actual call is the method B () in the base class B (). After the expansion, the base class B (), new, new The identification. For example, a method A () defined in the base class, rewritten A () and expanded in the derived class and expanded the B () method, working properly, HOHO release program. One month we rewritten the base class needs to expand a B () method so the program gives a compilation prompt. This time there is also a version of the version.

For the above problems above, override methods with virtual to prevent errors from calling!

转载请注明原文地址:https://www.9cbs.com/read-116345.html

New Post(0)