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

前端 未结 6 1690
栀梦
栀梦 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:24

    FYI, the feature you want is called "virtual method return type covariance", and as you have discovered, it is not supported by C#. It is a feature of other object-oriented languages, like C++.

    Though we get requests for this feature fairly frequently, we have no plans to add it to the language. It is not a terrible feature; if we had it, I'd use it. But we have many reasons not to do it, including that it is not supported by the CLR, it adds new and interesting failure modes to versionable components, Anders does not think it is a very interesting feature, and we have many, many higher priorities and a limited budget.

    Incidentally, though people ask us for virtual method return type covariance all the time, no one ever asks for virtual method formal parameter type contravariance, even though logically they are essentially the same feature. That is, I have a virtual method/interface method M that takes a Giraffe, and I would like to override it/implement it with a method M that takes an Animal.

提交回复
热议问题