override与new的区别

昨天参加面试,遇到一个关于new修饰符的题,由于本人不慎,给搞错了,纠其原因,还是因为我的C#基础知识不牢固,关于override与new的区别平时没有太注意。在此,为大家分享一下:
代码如下:


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    }


问题:
1、初始化一实例:baseClass tempClass=new derivedClass()之后,会输出什么结果?
2、把derivedClass类中的override换成 new之后,又会输出什么结果?

正确答案:
1、value!=2
2、Method1 in baseClass
MSDN上说:new 关键字在用作修饰符时,可以显式隐藏从基类继承的成员。隐藏继承的成员意味着该成员的派生版本将替换基类版本。也就是说,在用new关键字时,派生类与基类的这两个相同签名的方法已经没有任何联系了。
而用override时,它与new的区别主要是,overrid是重写了基类的方法,new是隐藏、覆盖了基类的方法。

引用至:http://www.cnblogs.com/anlyren/archive/2007/11/07/new.html

转载于:https://www.cnblogs.com/zhangchenliang/archive/2011/08/17/2142957.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值