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

前端 未结 3 1951
难免孤独
难免孤独 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:03

    The feature you're asking about is called "return type covariance". As noted on Wikipedia, Java and C++ both have it, which perhaps makes it surprising that C# does not.

    Eric Lippert confirms in the comments on this answer that this feature wasn't implemented because it wasn't deemed worth the implementation effort. (A previous revision of this answer assigned responsibility for that decision to Eric personally; he says that this is incorrect, and that if any one person is responsible it was Anders Hejlsberg.)

    Regardless, there are now various proposals to add it to the language (see https://github.com/dotnet/roslyn/issues/357, https://github.com/dotnet/csharplang/blob/master/proposals/covariant-returns.md, https://github.com/kingces95/coreclr/issues/2), so perhaps it will get implemented in the next couple of years. Per those discussions, it doesn't sound like there are any profound reasons why the feature shouldn't exist in C# in principle - rather, it's just never so far been judged worth anyone's effort to implement.

提交回复
热议问题