I often forget if i have to use in or out when defining covarient and contravarient generic types. In java i have the mnemonic PECS (producer extends consumer super) to help me. Do you know a similar mnemonic 开发者_StackOverflow中文版for c#?
Didn't they do this for us when they called them 'in' and 'out' rather than covariant and contravariant? Just think: am I pushing values 'in', or getting them 'out'? If unsure, try 'out' - it is far more common (and easier to understand).
in
types are passed in
to functions; out
types are returned out
from functions.
When I don't remember, I always refer to IEnumerable<out T>
(which means of course I have to remember the signature of that interface...). You can only get instances of T "out" of an IEnumerable<out T>
, so it is covariant. If you can only pass instances of T "in" to an interface (or delegate, which is more common), it's contravariant.
精彩评论