实现Icollection接口的对象
来源:互联网 发布:学编程 编辑:程序博客网 时间:2024/05/22 02:28
- class Test : System.Collections.ICollection
- {
- string[] _list;
- object _root = new object();
- public Test()
- {
- _list = new string[]{"abc","def","ghi","jkl","mno","pqr","stu","vwx","yz"};
- }
- #region ICollection 成员
- public bool IsSynchronized
- {
- get
- {
-
- return false;
- }
- }
- public int Count
- {
- get
- {
- return this._list.Length;
- }
- }
- public void CopyTo(Array array, int index)
- {
- foreach(string s in this._list)
- {
- array.SetValue(s,index);
- index ++;
- }
- }
- public object SyncRoot
- {
- get
- {
- return this;
- }
- }
- #endregion
- #region IEnumerable 成员
- public System.Collections.IEnumerator GetEnumerator()
- {
-
- return new MyEnum(this._list);
- }
- #endregion
- }
- class MyEnum : System.Collections.IEnumerator
- {
- string[] str;
- private int cursor;
- public MyEnum(string[] list)
- {
- this.str = list;
- this.cursor = -1;
- }
- #region IEnumerator 成员
- public void Reset()
- {
- this.cursor = -1;
- }
- public object Current
- {
- get
- {
- if((this.cursor < 0) || this.cursor == str.Length)
- {
- throw new InvalidOperationException();
- }
- return this.str[this.cursor];
- }
- }
- public bool MoveNext()
- {
- if(this.cursor < str.Length)
- this.cursor ++;
- return (!(this.cursor == str.Length));
- }
- #endregion
- }
如果要想ArrayList的方括号检索的话,还要继承IList接口,实现他的public Object this[index]{}方法就可以了