CollectionBase集合的基类

构造集合类,可以通过继承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
{
//这里可以自定义自己的 索引 包含 添加 删除 操作
 
}
原文地址:https://www.cnblogs.com/chenqingwei/p/1982013.html