C#: Property overriding by specifying the interface explicitly

后端 未结 1 1600
伪装坚强ぢ
伪装坚强ぢ 2020-12-31 03:51

While attempting to override the explicit interface implementation of the ICollection.IsReadOnly property from the Collection cla

相关标签:
1条回答
  • 2020-12-31 04:05

    This has nothing to do with explicit interface implementation; it's simply a consequence of the general rules of inheritance and interface mapping: you would see exactly the same results if type A provided an implicit, rather than explicit, implementation of IMyInterface.

    • Type B inherits from type A. Nothing is overridden.
      B provides its own AlwaysFalse and IsTrue members but they don't implement IMyInterface; The implementation of IMyInterface is provided by the members inherited from A: when an instance of type B is cast to IMyInterface then it behaves in exactly the same way as an instance of type A because A is providing the members that implement the interface.
    • Type C inherits from type A. Again, nothing is overridden.
      C provides its own AlwaysFalse and IsTrue members but this time those members do implement IMyInterface: when an instance of type C is cast to IMyInterface then the members of C provide the interface implementation rather than those of A.

    Because type A implements IMyInterface explicitly the compiler doesn't warn that the members of B and C are hiding the members of A; In effect those members of A were already hidden due to the explicit interface implementation.

    If you changed type A to implement IMyInterface implicitly rather than explicitly then the compiler would warn that the members of B and C are hiding, not overriding, the members of A and that you should ideally use the new modifier when declaring those members in B and C.

    Here are some relevant bits from the language specification. (Sections 20.4.2 and 20.4.4 in the ECMA-334 spec; sections 13.4.4 and 13.4.6 in the Microsoft C#4 spec.)

    20.4.2 Interface mapping

    The implementation of a particular interface member I.M, where I is the interface in which the member M is declared, is determined by examining each class or struct S, starting with C and repeating for each successive base class of C, until a match is located.

    20.4.4 Interface re-implementation

    A class that inherits an interface implementation is permitted to re-implement the interface by including it in the base class list. A re-implementation of an interface follows exactly the same interface mapping rules as an initial implementation of an interface. Thus, the inherited interface mapping has no effect whatsoever on the interface mapping established for the re-implementation of the interface.

    0 讨论(0)
提交回复
热议问题