IEnumerable, ICollection, IList,每種接口隻适合某些特定場景,如何差別使用呢?
IEnumerable接口,隻提供了一個擷取疊代器的方法,這也是為什麼可以使用foreach周遊實作了IEnumerable接口集合的原因。
public interface IEnumerable
{
IEnumerator GetEnumerator();
}
ICollection實作了IEnumerable接口,是以,除了擁有IEnumerable接口的能力,還包括其它能力。
public interface ICollection : IEnumerable
{
int Count{get;}
bool IsSynchronized{get;}
Object SyncRoot{get;}
IEnumerator GetEnumerator();
void CopyTo(Array array, int index);
}
IList同時實作了ICollection和IEnumerable接口,在2個接口的基礎上,可以添加、移除或清空集合,還提供了根據索引通路集合元素。
public interface IList : ICollection, IEnumerable
{
bool IsFixedSize{get;}
bool IsReadOnly{get;}
Object this[int index] {get;set;}
int Add(Object value);
void Clear();
bool Contains(Object value);
int IndexOf(Object value);
void Insert(int index, Object value);
void Remove(Object value);
void RemoveAt(int index);
}
總結:
● 如果隻想周遊集合,使用IEnumerable, IEnumerable<T>
● 如果想周遊、修改集合,以及需要延遲加載的導航屬性,使用ICollection, ICollection<T>
● 如果想周遊、修改、添加、清空、使用索引,使用IList, IList<T>