码迷,mamicode.com
首页 > Windows程序 > 详细

C# Keyword usage virtual + override VS new

时间:2015-01-22 10:52:14      阅读:183      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!