C#:我的派生类不能覆盖基类的接口方法实现,为什么?

vik*_*ata 0 c# inheritance implementation interface hide

我有下面的代码,我使用类"B"继承类"A",而我​​希望从接口IMy实现F函数.但是编译器告诉我我正在隐藏接口方法"F".所以运行结果是"A".

我希望这个程序输出"B".我不希望使用隐式接口实现,因为我希望在main函数中使用正常的多态性.

如何更正我的代码?谢谢.

public interface IMy
{
    void F();
}

public class A : IMy
{
    public void F()
    {
        Console.WriteLine("A");
    }
}

public class B : A
{
    public void F()
    {
        Console.WriteLine("B");
    }
}
class Program
{
    static void Main(string[] args)
    {
        IMy my = new B();
        my.F();
    }
}
Run Code Online (Sandbox Code Playgroud)

Jak*_*rtz 6

要覆盖C#中的方法,需要将基类中的方法显式标记为virtual.该方法是否实现接口方法无关紧要.

public class A : IMy
{
    public virtual void F()
    {
        Console.WriteLine("A");
    }
}

public class B : A
{
    public override void F()
    {
        Console.WriteLine("B");
    }
}
Run Code Online (Sandbox Code Playgroud)