c# – 使用虚拟方法覆盖抽象方法

c# – 使用虚拟方法覆盖抽象方法,第1张

概述我试图在子类中使用虚方法覆盖抽象类中的抽象方法.我(假设到现在?)了解抽象方法和虚方法之间的区别. 显然我无法做到,但我的问题是……为什么?基于接受的答案here和以下场景,我只是没有看到问题: public abstract class TopLevelParent { protected abstract void TheAbstractMethod(); } 我试图在子类中使用虚方法覆盖抽象类中的抽象方法.我(假设到现在?)了解抽象方法和虚方法之间的区别.

显然我无法做到,但我的问题是……为什么?基于接受的答案here和以下场景,我只是没有看到问题:

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

所以,我所做的就是让一个顶级父级有两个继承子级,另一个继承自其中一个继承子级.同样,根据我在上面发布的链接中接受的答案:

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

并且第二级子级将从其父级继承虚拟方法,从而满足其最顶层父级的抽象方法的实现要求……问题是什么?

我错过了某些阻碍我对此理解的细节……

解决方法 除非标记为 sealed,否则 override方法是隐式虚拟的(在某种意义上它可以在子类中重写).

注意:

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}
总结

以上是内存溢出为你收集整理的c# – 使用虚拟方法覆盖抽象方法全部内容,希望文章能够帮你解决c# – 使用虚拟方法覆盖抽象方法所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/1241003.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-06
下一篇2022-06-06

发表评论

登录后才能评论

评论列表(0条)

    保存