简体   繁体   English

从非抽象类继承

[英]Inherit from a non-abstract class

I have several classes which inherit from a BaseClass which has an abstract method called GetData.我有几个继承自 BaseClass 的类,BaseClass 有一个名为 GetData 的抽象方法。 In one of them I want to basically inherit from again and provide use a new method called GetArticles which I call from GetData.在其中一个中,我想基本上再次继承并提供使用一种名为 GetArticles 的新方法,我从 GetData 调用该方法。 Here's the code.这是代码。

public abstract class BaseClass
{
    internal abstract void GetData();
}

internal class FirstClass : BaseClass
{
    internal override void GetData()
    {
        // calls GetArticles
    }

    protected void GetArticles()
    {
    }
}

internal class SecondClass : FirstClass
{
    protected new void GetArticles()
    {
    }
}

GetArticles is never called in SecondClass . GetArticles永远不会在SecondClassSecondClass It calls the one in FirstClass , even though my object is of type SecondClass .它调用FirstClass那个,即使我的对象是SecondClass类型。 I can't make GetArticles in FirstClass Abstract because I want to use FirstClass in its own right.我无法在FirstClass Abstract创建GetArticles ,因为我想FirstClass使用FirstClass

Any suggestions?有什么建议?

Your method has to marked as virtual in FirstClass and overriden using override keyword in SecondClass .您的方法必须在FirstClass标记为virtual并在SecondClass使用override关键字override

internal class FirstClass : BaseClass
{
    internal override void GetData()
    {
        // calls GetArticles
    }

    protected virtual void GetArticles()
    {
    }
}

internal class SecondClass : FirstClass
{
    protected override void GetArticles()
    {
    }
}

new modifier hides the underlying virtual method, which is not what you want. new修饰符隐藏了底层的虚方法,这不是你想要的。 Check Knowing When to Use Override and New Keywords (C# Programming Guide) on MSDN.在 MSDN 上查看了解何时使用覆盖和新关键字(C# 编程指南)

Declare GetArticles in your FirstClass as virtual.FirstClass GetArticles声明为虚拟。 In the second class remove new and add override在第二个类中删除new并添加override

Make GetArticles virtual.使GetArticles虚拟化。

protected virtual void GetArticles()
{
}

Normal Class can not contain abstract method.Whereas abstract class can contain normal method.普通类不能包含抽象方法。而抽象类可以包含普通方法。 If a normal class inherit abstract class and hold any abstract method than must be override due to inheritance in derived class.如果普通类继承抽象类并持有任何抽象方法,则必须由于派生类中的继承而被覆盖。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM