Why can't an interface implementation return a more specific type?

前端 未结 3 1949
难免孤独
难免孤独 2021-01-07 16:18

If an interface specifies a property or method to return another interface, why is it not allowed for implementations of the first interface to \"change\" the return type in

3条回答
  •  南笙
    南笙 (楼主)
    2021-01-07 17:15

    Usually, I'd say that it would be a case of balancing the benefit against the added complexity of supporting such a feature. (All features take effort to design, document, implement, test, and then developers need to be educated about them too.) Note that there could be some significant complexities if you wanted to support returning a value type which implemented an interface, for example (as that ends up in a different representation, rather than just a reference).

    In this case, I don't believe the CLR even supports such a feature, which would make it very hard for C# to do so cleanly.

    I agree it would be a useful feature, but I suspect it hasn't been deemed useful enough to warrant the extra work required.

提交回复
热议问题