实现Icollection接口的对象

来源:互联网 发布:学编程 编辑:程序博客网 时间:2024/05/22 02:28
  1. class Test : System.Collections.ICollection
  2. {
  3.    string[] _list;
  4.    object _root = new object();
  5.    public Test()
  6.    {
  7.     _list = new string[]{"abc","def","ghi","jkl","mno","pqr","stu","vwx","yz"};
  8.    }
  9.    #region ICollection 成员
  10.    public bool IsSynchronized
  11.    {
  12.     get
  13.     {
  14.      // TODO: 添加 Test.IsSynchronized getter 实现
  15.      return false;
  16.     }
  17.    }
  18.    public int Count
  19.    {
  20.     get
  21.     {
  22.      return this._list.Length;
  23.     }
  24.    }
  25.    public void CopyTo(Array array, int index)
  26.    {
  27.     foreach(string s in this._list)
  28.     {
  29.      array.SetValue(s,index);
  30.      index ++;
  31.     }
  32.    }
  33.    public object SyncRoot
  34.    {
  35.     get
  36.     {
  37.      return this;
  38.     }
  39.    }
  40.    #endregion
  41.    #region IEnumerable 成员
  42.    public System.Collections.IEnumerator GetEnumerator()
  43.    {
  44.     // TODO: 添加 Test.GetEnumerator 实现
  45.     return new MyEnum(this._list);
  46.    }
  47.    #endregion
  48. }
  49. class MyEnum : System.Collections.IEnumerator
  50. {
  51.    string[] str;
  52.    private int cursor;
  53.    public MyEnum(string[] list)
  54.    {
  55.     this.str = list;
  56.     this.cursor = -1;
  57.    }
  58.    #region IEnumerator 成员
  59.    public void Reset()
  60.    {
  61.     this.cursor = -1;
  62.    }
  63.    public object Current
  64.    {
  65.     get
  66.     {
  67.      if((this.cursor < 0) || this.cursor == str.Length)
  68.      {
  69.       throw new InvalidOperationException();
  70.      }
  71.      return this.str[this.cursor];
  72.     }
  73.    }
  74.    public bool MoveNext()
  75.    {
  76.     if(this.cursor < str.Length)
  77.      this.cursor ++;
  78.     return (!(this.cursor == str.Length));
  79.    }
  80.    #endregion
  81. }
 如果要想ArrayList的方括号检索的话,还要继承IList接口,实现他的public Object this[index]{}方法就可以了
原创粉丝点击