c# - 如果虚方法被声明为抽象的

标签 c# oop inheritance polymorphism

我的 friend 问我抽象 方法是否可以有virtual 修饰符。我说,。 因为,抽象方法隐式也是虚方法,它不能有修饰符 virtual。

但在阅读时one of the MSDN articles ,我见过这个:

... If a virtual method is declared abstract, it is still virtual to any class inheriting from the abstract class. A class inheriting an abstract method cannot access the original implementation of the method—in the previous example, DoWork on class F cannot call DoWork on class D. In this way, an abstract class can force derived classes to provide new method implementations for virtual methods....

我无法正确理解第一句话。你能解释一下他们想说什么吗?

谢谢。

最佳答案

当您查看引用段落正上方的代码示例时,它会变得更加清晰:

public class D
{
    public virtual void DoWork(int i)
    {
        // Original implementation.
    }
}

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

虚方法 D.DoWorkE 继承,并在那里声明为抽象方法。该方法仍然是虚拟的,只是变得抽象

正如您所说的那样,抽象方法始终是虚拟的。如果您的 friend 仍然不服气,这里有一个 official quote为此:

An abstract method is implicitly a virtual method.

关于c# - 如果虚方法被声明为抽象的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25472654/

相关文章:

c# - 从 SQL Server 数据库格式化十进制值

c# - C#中的VirtualAlloc分配大内存

c# - 创建代表一系列连续任务的任务

javascript - 面向对象的 d3

oop - OOD - 杯子的内容是 Mug 类的属性?

java - ActionListener 无法识别来自主类的变量

c# - Windows Mobile : exception in Finalizer terminates program

oop - 使用哪种设计模式进行顺序操作和重试

c++ - 类型在编译时已知的虚拟方法

c++ - 重载继承的构造函数