虚方法和抽象方法的区别 [英] Difference between virtual and abstract methods

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

问题描述

这是来自 MSDN 的一些代码:

Here is some code from 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.
    }
}

谁能解释一下上面代码中抽象方法和虚拟方法的区别?

Can anyone explain the above code with respect to the differences between abstract and virtual methods?

推荐答案

虚拟方法有一个实现,并为派生类提供覆盖它的选项.抽象方法不提供实现并强制派生类覆盖该方法.

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

因此,抽象方法中没有实际代码,子类必须覆盖该方法.虚拟方法可以有代码,这通常是某些东西的默认实现,任何子类都可以使用 override 修饰符覆盖该方法并提供自定义实现.

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天全站免登陆