The meanings of these two keywords are easy to understand, but you may not be able to quickly write the correct answers to the following questions. If you do not believe them, try again.
1. Differences between new and override
View Code
Public abstract class
{
Public ()
{
Console. writeline ('A ');
}
Public Virtual void fun ()
{
Console. writeline ("A. Fun ()");
}
}
Public Class B:
{
Public B ()
{
Console. writeline ('B ');
}
Public new void fun ()
{
Console. writeline ("B. Fun ()");
}
Public static void main ()
{
A A = new B ();
A. Fun ();
Console. Read ();
}
}
What is the output of this code?
Basic principle: override is used to override the base class method, and new is used to hide the derived class of the base class.
There is no difference if you use the type to call its own method
For example
A A = new A (); A. Fun ();
B = new B (); B. Fun ();
Such a call is the same as calling a common member method, and the result is the output of their own method.
If you call a method by referencing the base class, the difference between new and override will come out.
Override can find the method defined in the True Type of the object, while new is just to find the method in the type definition.
The result is as follows:
2 virtual and override
The Code is as follows:
Public Class
{
Public Virtual void fun1 (int I)
{
Console. writeline (I );
}
Public void fun2 ()
{
A. fun1 (1 );
Fun1 (5 );
}
}
Public Class B:
{
Public override void fun1 (int I)
{
Base. fun1 (I + 1 );
}
Public static void main ()
{
B = new B ();
A A = new ();
A. fun2 (B );
B. fun2 ();
}
}
This code is also very strange, and the head is dizzy.
The result is as follows:
Sometimes writeProgramIt takes a lot of effort to carefully view the results.
You will be dizzy if you have the following questions:
Call time of type Initiators