The difference between override and new

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:


None.gif   public   class  baseClass
ExpandedBlockStart.gif    
{
InBlock.gif        
public baseClass()
ExpandedSubBlockStart.gif        
{
InBlock.gif            Method1();
ExpandedSubBlockEnd.gif        }

InBlock.gif        
public virtual void Method1()
ExpandedSubBlockStart.gif        
{
InBlock.gif            Console.WriteLine(
"Method1 in baseClass");
ExpandedSubBlockEnd.gif        }

ExpandedBlockEnd.gif    }

None.gif
None.gif    
public   class  derivedClass : baseClass
ExpandedBlockStart.gif    
{
InBlock.gif        
private int value;
InBlock.gif        
public derivedClass()
ExpandedSubBlockStart.gif        
{
InBlock.gif            value 
= 2;
ExpandedSubBlockEnd.gif        }

InBlock.gif        
public override void Method1()
ExpandedSubBlockStart.gif        
{
InBlock.gif            
if (value == 2)
InBlock.gif                Console.WriteLine(
"value==2");
InBlock.gif            
else
InBlock.gif                Console.WriteLine(
"value!=2");           
ExpandedSubBlockEnd.gif        }

ExpandedBlockEnd.gif    }


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

Guess you like

Origin blog.csdn.net/weixin_33717117/article/details/93494973