用虚拟方法覆盖抽象方法 [英] Overriding an abstract method with a virtual one

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

问题描述

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

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:


一个虚函数,基本上是说看看,这里是功能
对于子类来说可能是也可能不够好。所以如果
足够好,请使用此方法,如果没有,则覆盖我,并提供
您自己的功能。

"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."

并且二级子级将从其父级继承虚方法,从而满足抽象方法的顶层实现要求大多数父母......问题是什么?

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...

推荐答案

覆盖 方法 隐式虚拟(在某种意义上它可以在子类中重写),除非标记为 已密封

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
}

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

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