Usage of keywords “in” and “out” in C#(.NET 4.0)

來源:互聯網
上載者:User

Variance will only be supported in a safe way - in fact, using the abilities that the CLR already has. So the examples I give in the book of trying to use a List<Banana> as a List<Fruit> (or whatever it was) still won't work - but a few other scenarios will.

Firstly, it will only be supported for interfaces and delegates.

Secondly, it requires the author of the interface/delegate to decorate the type parameters as in (for contravariance) or out (for covariance). The most obvious example is IEnumerable<T> which only ever lets you take values "out" of it - it doesn't let you add new ones. That will becomeIEnumerable<out T>. That doesn't hurt type safety at all, but lets you return anIEnumerable<string> from a method declared to return IEnumerable<object> for instance.

Contravariance is harder to give concrete examples for using interfaces, but it's easy with a delegate. Consider Action<T> - that just represents a method which takes a T parameter. It would be nice to be able to convert seamlessly use an Action<object> as an Action<string> - any method which takes an object parameter is going to be fine when it's presented with a string instead. Of course, C# 2 already has covariance and contravariance of delegates to some extent, but via an actual conversion from one delegate type to another (creating a new instance) - see P141-144 for examples. C# 4 will make this more generic, and (I believe) will avoid creating a new instance for the conversion. (It'll be a reference conversion instead.)

Hope this clears it up a bit - please let me know if it doesn't make sense!

referenced from: http://stackoverflow.com/questions/245607/how-is-generic-covariance-contra-variance-implemented-in-c-4-0 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.