简体   繁体   English

接口继承-从父接口隐藏方法-为什么在实现类中可以同时使用这两种方法?

[英]Interface inheritance - hiding method from parent interface - why can I have both methods in the implementing class?

I am trying to understand how the inheritance of interfaces works. 我试图了解接口的继承方式。 When an interface inherits another interface but has a method with the same signature, the compiler gives a warning that the base member is hidden (and this seems logical). 当一个接口继承另一个接口但具有一个具有相同签名的方法时,编译器会警告该基本成员已隐藏(这似乎是合乎逻辑的)。

However, when I later implement the child interface in a class, I have to implement both the parent and the child interface method having the same signature and this confuses me... I thought that when the parent member is hidden I will need to implement only the child interface method? 但是,当我稍后在类中实现子接口时,我必须实现具有相同签名的父接口和子接口方法,这使我感到困惑……我认为当父成员隐藏时,我将需要实现只有子界面方法?

(I came upon this while looking at IEnumerable and IEnumerable<T> interfaces) (我在查看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();
    }
}

I have to implement both the parent and the child interface method having the same signature and this confuses me 我必须实现具有相同签名的父接口和子接口方法,这使我感到困惑

So what do you expect will happen if you do this? 那么,如果您这样做,您会期望发生什么?

IMyBase x = new myClass();

x.DoSomething();

There is two methods, IMyBase.Something and IMyDerived.Something , both have to exist because both can be called. 有两种方法IMyBase.SomethingIMyDerived.Something都必须存在,因为两者都可以被调用。 myClass still implements IMyBase , the interface was not hidden in any way. myClass仍实现IMyBase ,该接口未以任何方式隐藏。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM