【问题标题】:Interface inheritance - hiding method from parent interface - why can I have both methods in the implementing class?接口继承-从父接口隐藏方法-为什么我可以在实现类中同时拥有这两种方法?
【发布时间】:2017-09-22 09:15:46
【问题描述】:

我试图了解接口的继承是如何工作的。当一个接口继承了另一个接口但有一个具有相同签名的方法时,编译器会给出一个警告,指出基成员是隐藏的(这似乎是合乎逻辑的)。

但是,当我稍后在一个类中实现子接口时,我必须实现具有相同签名的父接口和子接口方法,这让我感到困惑......我认为当父成员被隐藏时,我会只需要实现子接口方法吗?

(我在查看IEnumerableIEnumerable<T> 接口时发现了这一点)

interface IMyBase
{
    int DoSomething();
}

interface IMyDerived:IMyBase
{
    int DoSomething();
}


class myClass : IMyDerived
{
    int IMyDerived.DoSomething()
    {
        throw new NotImplementedException();
    }

    int IMyBase.DoSomething()
    {
        throw new NotImplementedException();
    }
}

【问题讨论】:

  • 你明确地实现了接口。在这种情况下,继承是不可能的。
  • 接口成员无法隐藏没有类
  • 只是不要将DoSomething() 放在IMyDerived 中,它已经从IMyBase 继承了它。把它放在这个界面中会增加零值。我真的很惊讶编译器没有抱怨这个?我希望至少有一个警告。

标签: c# interface method-hiding


【解决方案1】:

我必须实现具有相同签名的父接口方法和子接口方法,这让我感到困惑

那么如果你这样做,你期望会发生什么?

IMyBase x = new myClass();

x.DoSomething();

有两种方法,IMyBase.SomethingIMyDerived.Something,它们都必须存在,因为它们都可以被调用。 myClass 仍然实现了IMyBase,接口没有以任何方式隐藏。

【讨论】:

  • 在这种情况下,编译器的消息“MyDerived.DoSomething()'隐藏了继承的成员'IMyBase.DoSomething()'...”是什么意思?它隐藏在哪个上下文中?
  • @Jaxx 通过IMyDerived 类型调用时,IMyBase.DoSomething 被隐藏。您必须先转换为 IMyBase 才能访问 that 方法。
猜你喜欢
  • 2013-06-11
  • 1970-01-01
  • 2021-07-20
  • 1970-01-01
  • 1970-01-01
  • 2020-12-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多