用虚拟方法覆盖抽象方法

用虚拟方法覆盖抽象方法

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

问题描述

我试图用子类中的虚拟方法覆盖抽象类中的抽象方法.我(假设到现在?)理解抽象方法和虚拟方法之间的区别.

I'm trying to override an abstract method in an abstract class with a virtual method in a child class. I (assumed until now?) understand the difference between abstract and virtual methods.

显然我做不到,但我的问题是......为什么?基于接受的答案此处 和以下场景,我只是没有看到问题:

Obviously I'm not able to do it but my question is... why? Based on the accepted answer here and the following scenario, I just don't see the problem:

    public abstract class TopLevelParent
    {
        protected abstract void TheAbstractMethod();
    }

    public class FirstLevelChild1 : TopLevelParent
    {
        protected override void TheAbstractMethod()
        {

        }
    }

    public class FirstLevelChild2 : TopLevelParent
    {
        protected virtual override void TheAbstractMethod()
        {
            //Do some stuff here
        }
    }

    public class SecondLevelChild : FirstLevelChild2
    {
        //Don't need to re-implement the method here... my parent does it the way I need.
    }

所以很明显,我所做的是有一个顶级父级,它有两个继承子级和另一个继承自其中一个子级的类.同样,基于我在上面发布的链接中接受的答案:

So obviosuly what I've done is have a top-level parent with two inheriting children and another class inheriting from one of those. Again, based on the accepted answer in the link I posted above:

"一个虚函数,基本上是说看,这里是功能这对儿童班来说可能不够好,也可能不够.所以如果是足够好,使用这个方法,如果没有,然后覆盖我,并提供您自己的功能."

而且二级子级会继承父级的虚方法,从而满足最顶层父级抽象方法的实现需求……有什么问题?

and that the second level child will inherit the virtual method from its parent, thus satisfying the implementation requirement of the abstract method from its top-most parent... what's the problem?

我在某处遗漏了一些妨碍我理解这一点的细节......

I'm missing some detail somewhere that's hindering my understanding of this...

推荐答案

override 方法隐式虚拟的(从某种意义上说,它可以在子类中被覆盖),除非标记为 密封.

An override method is implicitly virtual (in the sense that it can be overridden in a subclass), unless marked as sealed.

观察:

public class FirstLevelChild1 : TopLevelParent
{
    protected override void TheAbstractMethod() { }
}

public class SecondLevelChild1 : FirstLevelChild1
{
    protected override void TheAbstractMethod() { } // No problem
}

public class FirstLevelChild2 : TopLevelParent
{
    protected sealed override void TheAbstractMethod() { }
}

public class SecondLevelChild : FirstLevelChild2
{
    protected override void TheAbstractMethod() { }
    // Error: cannot override inherited member
    // 'FirstLevelChild2.TheAbstractMethod()' because it is sealed
}

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

07-24 17:18