An abstract function has to be overridden while a virtual function may be overridden.
Virtual functions can have a default /generic implementation in the base class.
An abstract function can have no functionality. You‘re basically saying, any child class MUST give their own version of this method, however it‘s too general to even try to implement in the parent class. A virtual function, is basically saying look, here‘s the functionality that may or may not be good enough for the child class. So if it is good enough, use this method, if not, then override me, and provide your own functionality.
public class BaseClass { public void SayHello() { Console.WriteLine("Hello"); } public virtual void SayGoodbye() { Console.WriteLine("Goodbye"); } public void HelloGoodbye() { this.SayHello(); this.SayGoodbye(); } } public class DerivedClass : BaseClass { public new void SayHello() { Console.WriteLine("Hi There"); } public override void SayGoodbye() { Console.WriteLine("See you later"); } }
When I instantiate DerivedClass
and call SayHello
, or SayGoodbye
, I get "Hi There" and "See you later". If I call HelloGoodbye
, I get "Hello" and "See you later". This is because SayGoodbye
is virtual, and can be replaced by derived classes. SayHello
is only hidden, so when I call that from my base class I get my original method.
Abstract methods are implicitly virtual. They define behavior that must be present, more like an interface does.
这里new 关键字的作用
在用作修饰符时,new 关键字可以显式隐藏从基类继承的成员。隐藏继承的成员意味着该成员的派生版本将替换基类版本。在不使用 new 修饰符的情况下隐藏成员是允许的,但会生成警告。使用 new 显式隐藏成员会取消此警告,并记录代之以派生版本这一事实。若要隐藏继承的成员,请使用相同名称在派生类中声明该成员,并使用 new 修饰符修饰该成员
http://msdn.microsoft.com/zh-cn/library/sf985hc5.aspx
http://msdn.microsoft.com/zh-cn/library/9fkccyh4.aspx
http://msdn.microsoft.com/en-us/library/aa645767(v=vs.71).aspx
http://msdn.microsoft.com/en-us/library/aa664435(v=vs.71).aspx