The return type of the members on an Interface Implementation must match exactly the interface definition?

前端 未结 6 1695
栀梦
栀梦 2020-12-05 11:58

According to CSharp Language Specification.

An interface defines a contract that can be implemented by classes and structs. An interface does not p

6条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-05 12:42

    Simple fact is, if an interface says:

    IInterface{
       Animal A { get; }
    }
    

    Then an implementation of that property must match the type exactly. Trying to implement it as

    MyClass : IInterface{
      Duck A { get; }
    }
    

    Does not work - even though Duck is an Animal

    Instead you can do this:

    MyClass : IInterface{
      Duck A { get; }
      Animal IInterface.A { get { return A; } }
    }
    

    I.e. provide an explicit implementation of the IInterface.A member, exploiting the type relationship between Duck and Animal.

    In your case this means implementing, the getter at least, ITest.Integers as

    IEnumerable ITest.Integers { get { return Integers; } }
    

    To implement the setter, you will need to cast optimistically or use .ToList() on the input value.

    Note that the use of A and Integers inside these explicit implementations is not recursive because an explicit interface implementation is hidden from the public view of a type - they only kick in when a caller talks to the type through it's IInterface/ITest interface implementation.

提交回复
热议问题