【问题标题】:C#: my derived class cannot override base class's interface method implementation, why?C#:我的派生类不能覆盖基类的接口方法实现,为什么?
【发布时间】:2016-06-14 18:12:38
【问题描述】:

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

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

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

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();
    }
}

【问题讨论】:

    标签: c# inheritance interface hide implementation


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      您当前的代码相当于:

      public class A : IMy
      {
          public void F()
          {
              Console.WriteLine("A");
          }
      }
      
      public class B : A
      {
          public new void F() // <--- Note 'new' here
          {
              Console.WriteLine("B");
          }
      }
      

      您隐含地将方法标记为新方法,除非您明确编写它,否则将生成编译器警告。

      你真正想要的是重写方法,所以声明:

      public class A : IMy
      {
          public virtual void F() // <--- Mark as virtual to allow subclasses to override
          {
              Console.WriteLine("A");
          }
      }
      
      public class B : A
      {
          public override void F() // <-- Override the method rather than hiding it
          {
              Console.WriteLine("B");
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2012-05-14
        • 2013-09-30
        • 2012-03-14
        • 1970-01-01
        • 2018-09-21
        • 2010-09-22
        • 2015-05-22
        • 2012-12-04
        • 1970-01-01
        相关资源
        最近更新 更多