Interview yesterday, encountered a problem on new modifier, because of my mistake, to mistake, correct reason, or because my basic knowledge of C # is not solid, the difference on the override and new usually do not pay much attention. Here, for everyone to share:
code is as follows:
public class baseClass
{
public baseClass()
{
Method1();
}
public virtual void Method1()
{
Console.WriteLine("Method1 in baseClass");
}
}
public class derivedClass : baseClass
{
private int value;
public derivedClass()
{
value = 2;
}
public override void Method1()
{
if (value == 2)
Console.WriteLine("value==2");
else
Console.WriteLine("value!=2");
}
}
Question:
1, initializing an example: After baseClass tempClass = new derivedClass (), what will output the results?
2, the derivedClass class override later replaced by new, what will output the results?
The correct answer:
! 1, 2 = value
2, Method1 in baseClass
on MSDN say: new keyword when used as a modifier, you can explicitly hide a member inherited from a base class. Hide Inherited means that the members of the derived version will replace the member of the base class version. That is, when using the new keyword, the derived class with the same signature as the two base class has no contacted.
While with the override, which is the difference between the new primary, overrid rewrite the base class methods, new is hidden, the method of covering the base class.
References to: http://www.cnblogs.com/anlyren/archive/2007/11/07/new.html
Reproduced in: https: //www.cnblogs.com/zhangchenliang/archive/2011/08/17/2142957.html