首页 > Windows开发 > 详细

C# Keyword usage virtual + override VS new

时间:2015-01-22 10:49:39      阅读:309      评论:0      收藏:0      [点我收藏+]

A simple case:

public class Foo
{
     public /*virtual*/ bool DoSomething() { return false; }
}

public class Bar : Foo
{
     public /*override or new*/ bool DoSomething() { return true; }
}

Call the code like this:

Foo a = new Bar();
a.DoSomething();

NOTE: The important thing is that our object is actually a Bar, but we are storing it in a variable of type Foo (this is similar to casting it)

 

Explain:

New keyword is for Hiding. - means you are hiding your method at runtime. Output will be based base class method.

Override for overriding. - means you are invoking your derived class method with the reference of base class. Output will be based on derived class method.

Check out the  following link for more discussion:

http://stackoverflow.com/questions/159978/c-sharp-keyword-usage-virtualoverride-vs-new

 

C# Keyword usage virtual + override VS new

原文:http://www.cnblogs.com/freecodeX/p/4240975.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!