構造集合類,可以通過繼承CollectionBase,而CollectionBase實現了IList、ICollection、IEnumerable介面。
IEnumerable介面實現了 GetEnumerator()方法,實現了對結果的枚舉。
// 摘要: // 公開枚舉數,該枚舉數支援在非泛型集合上進行簡單迭代。 [ComVisible(true)] [Guid("496B0ABE-CDEE-11d3-88E8-00902754C43A")] public interface IEnumerable { // 摘要: // 返回一個逐一查看集合的枚舉數。 // // 返回結果: // 可用於逐一查看集合的 System.Collections.IEnumerator 對象。 [DispId(-4)] IEnumerator GetEnumerator(); }
ICollection 繼承自IEnumerable介面,在些基礎上添加了三個屬性與一個方法。
int Count { get; } bool IsSynchronized { get; } object SyncRoot { get; } void CopyTo(Array array, int index);
IList介面實現了以上二個介面 又添加了新的屬性與方法
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);
object this[int index] { get; set; }
bool IsReadOnly { get; }
bool IsFixedSize { get; }
現在回到CollectionBase類中 ,首先看一下類的定義
public abstract CollectionBase : IList, ICollection, IEnumerable
{
//建構函式
protected CollectionBase();
protected CollectionBase(int capacity);
//屬性定義
public int Capacity{get; set;}
public int Count{get;}
protected ArrayList InnerList{get;}
protected IList List{get;}
//方法定義
public void Clear();
public IEnumerable GetEnumerator();
protected virtual void OnClear();
protected virtual void OnClearComplete();
protected virtual void OnInsert(int index, object value);
protected virtual void OnInsertComplete(int inedx, object value);
protected virtual void OnRemove(int index, object value);
protected virtual void OnRemove(int index, object value, object newValue);
protected virtual void OnSet(int index, object oldValue, object newValue);
protected virtual void OnSetComplete(int index, object oldValue, object newValue);
protected virtual void OnValidate(object value);
public void RemoveAt(int index);
}
自訂集合類時可以擴充CollectionBase
public sealed class MyCollection : CollectionBase
{
//這裡可以自訂自己的 索引 包含 添加 刪除 操作
}