An abstract method overrides an abstract method

与世无争的帅哥 提交于 2019-12-04 03:28:22

问题


public abstract class A
{
    public abstract void Process();
}

public abstract class B : A
{
    public abstract override void Process();
}

public class C : B
{
    public override void Process()
    {
        Console.WriteLine("abc");
    }
}

This code throws an Compilation Error: 'B' does not implement inherited abstract member 'A.Process()'.

Is there any way to do this?


回答1:


Just leave out the method completely in class B. B inherits it anyway from A, and since B itself is abstract, you do not explicitly need to implement it again.




回答2:


Works for me in VS2008; no errors, no warnings. BUT, there's no reason to have the 'override' in B. This code is equivalent:

public abstract class A
{
    public abstract void Process();
}

public abstract class B : A
{
}

public class C : B
{
    public override void Process()
    {
        Console.WriteLine("abc");
    }
}



回答3:


Alon -

This makes no sense. First of all, this does actually compile fine. Secondly, the abstract method you declared in A is inherited (still abstract) into B. Therefore, you have no need to declare Process() in class B.

-- Mark




回答4:


The place where I've seen this sometimes is overriding a non-abstract virtual method with an abstract method. For example:

public abstract class SomeBaseType
{
    /* Override the ToString method inherited from Object with an abstract
     * method. Non-abstract types derived from SomeBaseType will have to provide
     * their own implementation of ToString() to override Object.ToString().
     */
    public abstract override string ToString();
}

public class SomeType : SomeBaseType
{
    public override string ToString()
    {
        return "This type *must* implement an override of ToString()";
    }
}


来源:https://stackoverflow.com/questions/1768977/an-abstract-method-overrides-an-abstract-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!