虚拟和抽象方法的区别 [英] Difference between Virtual and Abstract Methods

查看:198
本文介绍了虚拟和抽象方法的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是 MSDN

    // compile with: /target:library 
public class D
{
    public virtual void DoWork(int i)
    {
        // Original implementation.
    }
}

public abstract class E : D
{
    public abstract override void DoWork(int i);
}

public class F : E
{
    public override void DoWork(int i)
    {
        // New implementation.
    }
}

任何一个可以与抽象和虚拟methods.i区别解释上述code得到全乱了试图找出他们所要表达的意思。

can any one explain the above code with difference between abstract and virtual methods.i got all messed up trying to figure out what they are trying to say.

推荐答案

虚拟方法都有一个实现,并提供派生类与覆盖它的选项。抽象方法不提供实施和强制派生类要覆盖的方法。

Virtual methods have an implementation and provide the derived classes with the option of overriding it. Abstract methods do not provide an implementation and forces the derived classes to override the method.

所以,抽象方法对他们有没有实际的code和子类必须覆盖的方法。虚方法可以有code,这是通常的东西默认实现,任何子类可以使用覆盖修改覆盖的方法,并提供一个自定义的实现。

So, abstract methods have no actual code in them, and subclasses HAVE TO override the method. Virtual methods can have code, which is usually a default implementation of something, and any subclasses CAN override the method using the override modifier and provide a custom implementation.

public abstract class E
{
    public abstract void AbstractMethod(int i);

    public virtual void VirtualMethod(int i)
    {
        // Default implementation which can be overridden by subclasses.
    }
}

public class D : E
{
    public override void AbstractMethod(int i)
    {
        // You HAVE to override this method
    }
    public override void VirtualMethod(int i)
    {
        // You are allowed to override this method.
    }
}

这篇关于虚拟和抽象方法的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆