List<T> or IList<T>

Can anyone explain to me why I would want to use IList over List in C#?

Related question: Why is it considered bad to expose List<T>


If you are exposing your class through a library that others will use, you generally want to expose it via interfaces rather than concrete implementations. This will help if you decide to change the implementation of your class later to use a different concrete class. In that case the users of your library won't need to update their code since the interface doesn't change.

If you are just using it internally, you may not care so much, and using List<T> may be ok.


The less popular answer is programmers like to pretend their software is going to be re-used the world over, when infact the majority of projects will be maintained by a small amount of people and however nice interface-related soundbites are, you're deluding yourself.

Architecture Astronauts. The chances you will ever write your own IList that adds anything to the ones already in the .NET framework are so remote that it's theoretical jelly tots reserved for "best practices".

Obviously if you are being asked which you use in an interview, you say IList, smile, and both look pleased at yourselves for being so clever. Or for a public facing API, IList. Hopefully you get my point.


Interface is a promise (or a contract).

As it is always with the promises - smaller the better .

链接地址: http://www.djcxy.com/p/53922.html

上一篇: Linq Count()比List.Count或Array.Length更快还是更慢?

下一篇: 列表<T>或IList <T>