C#中的Collection 3

IList<T> 和 ICollection<T>

最重要的一些类型

List<T>: Encapsulates[T], like array, but also provide with adding/removing elemnts

ReadOnlyCollection<T>: Read-only wrapper for lists

Collection<T>: Allow lists to be customized

ObservableCollection<T>: List with changes notifications

 

 List<T>

What: List<T>是IList<T>的一种implementation

 

 + 

Can do:

IList<T> - access by index

IEnumerable<T> - foreach

ICoolection<T> - Collection initialzers

Array - All array can do

Collection<T>

是IList<T>的另一种Implementation

比如:我们建立一个list must only accept non-blank, non-null strings. 用List<T>就不成

方法:

如上图,Collection<T> encapsulate 了List<T>,其含有ICollection interface为其带来的Add()方法,和IList<T>的insert和this[index],但是这些方法都不可以重写。

幸运的是这些方法都会call底层的一个virtual方法,insertItem和setItem,我们可以重写这两个方法,从而 customize 我们的collection。

ObervableCollection<T>

主要是利用里面的CollectionChanged event, 其实他也是从Collection<T> customize出来的特殊类型,microsoft自己也经常用collection<T>做一些custmize的事情

 

 

 

原文地址:https://www.cnblogs.com/shawnzxx/p/3682450.html