C# abstract function VS virtual function?

本文对比了抽象函数与虚函数的区别,阐述了它们在继承与多态中的作用。通过示例代码展示了如何使用虚函数与抽象函数实现多态行为。

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

转载于:https://www.cnblogs.com/viviancc/p/3956359.html

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值