开发者

Covariance and Contravariance [duplicate]

开发者 https://www.devze.com 2023-01-13 15:27 出处:网络
This question already has answers here: Closed 12 years ago. Possible Duplicates: Covariance and contravariance real world example
This question already has answers here: Closed 12 years ago.

Possible Duplicates:

Covariance and contravariance real world example

still confused about covariance and contravariance & in/out

Can you give me a description or example of both covariance and cont开发者_如何学Goravaiance, and why they now decided to add it to .NET 4?


If B inherits from A, ie is a subtype of A, then C function is covariant if C(B) is a subtype of C(A), contravariant if C(A) is a subtype of C(B).

The question is wether or not you want consumers to deal with supertypes or subtypes.

A common example is a class library dealing in fruit classes.

It is OK for me to give you an apple where you expect a fruit. It is not OK for me to give you just any fruit where you expect an apple.

If you were making a fruit library. You should be expecting instances fruit from me and I should be expecting instances of fruit from you. Neither of us should have expectations about a subtype that could be false.

Therefore, the answer to the question above depends on wether you're getting or sending. Wether the parameter is read or write. A fruit list should be accepting bananas or apples, but only send "fruits"


Since there is no answer given I just summarize the comments

stackoverflow.com/questions/245607/ – MainMa

stackoverflow.com/questions/2662369/ stackoverflow.com/questions/1163465/ stackoverflow.com/questions/3445631/ – In Sane 56 mins ago

0

精彩评论

暂无评论...
验证码 换一张
取 消