码迷,mamicode.com
首页 > 其他好文 > 详细

C# abstract function VS virtual function?

时间:2014-09-04 18:33:39      阅读:153      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   os   io   使用   ar   for   

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://stackoverflow.com/questions/391483/what-is-the-difference-between-an-abstract-function-and-a-virtual-function\

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

C# abstract function VS virtual function?

标签:style   blog   http   color   os   io   使用   ar   for   

原文地址:http://www.cnblogs.com/viviancc/p/3956359.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!