如何覆盖从基类继承的方法,而基类又从接口实现它?

pyo*_*yon 1 c#

我有一个继承自A类的B类,它继承自接口I.这个接口公开了一个方法M,当然是由A实现的,但是我想在B中覆盖它.而且,我想要调用A.MB.M.我怎么做?


编辑:答案让我觉得有点愚蠢,特别是因为我知道什么virtual意思,事实上,我已经尝试过:

class A
{
    virtual void I.M()           // fails
Run Code Online (Sandbox Code Playgroud)

我从未考虑过没有明确地实现接口.

谢谢你们.

Jon*_*eet 9

好吧,要么你需要在A中使用虚拟方法,要么需要重新实现B中的接口,这会变得混乱.这是更简单的版本:

using System;

public interface IFoo
{
    void M();
}

public class A : IFoo
{
    public virtual void M()
    {
        Console.WriteLine("A.M");
    }
}

public class B : A
{
    public override void M()
    {
        base.M();
        Console.WriteLine("B.M");
    }
}

class Test
{
    static void Main()
    {
        IFoo foo = new B();
        foo.M();
    }
}
Run Code Online (Sandbox Code Playgroud)

...这里是重新实现的版本IFoo,隐藏 A.M()而不是覆盖它:

using System;

public interface IFoo
{
    void M();
}

public class A : IFoo
{
    public void M()
    {
        Console.WriteLine("A.M");
    }
}

public class B : A, IFoo
{
    public new void M()
    {
        base.M();
        Console.WriteLine("B.M");
    }
}

class Test
{
    static void Main()
    {
        IFoo foo = new B();
        foo.M();
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,如果您有:

A a = (A) foo;
a.M();
Run Code Online (Sandbox Code Playgroud)

只会打电话A.M(),而不是B.M().