开发者

Mnemonic for C# generic types

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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜