/*说明: 要使类支持foreach,有以几种方式: 1.IEnumerable,IEnumerator 2.IEnumerable<>,IEnumerator<> 3.自定义能返回IEnumerator的GetEnumerator()方法 */ #region 1.IEnumerable,IEnumerator public class Person { private string name; public string Name { get { return name; } set { name = value; } } } public class PersonCollection : System.Collections.IEnumerable { private System.Collections.Generic.List<Person> persons = new List<Person>(); public Person this[int index] { get { return persons[index]; } } public void Add(Person p) { persons.Add(p); } #region IEnumerable 成员 public System.Collections.IEnumerator GetEnumerator() { return new PersonEnumerator(persons); } #endregion private class PersonEnumerator : System.Collections.IEnumerator { List<Person> person; int position = -1; public PersonEnumerator(List<Person> thePerson) { this.person = thePerson; } #region IEnumerator 成员 public object Current { get { return this.person[position]; } } public bool MoveNext() { if (position < person.Count - 1) { position++; return true; } else { return false; } } public void Reset() { this.position = -1; } #endregion } } #endregion #region 2.IEnumerable<>,IEnumerator<> public class CommCollection<T> : System.Collections.Generic.IEnumerable<T> { private System.Collections.Generic.List<T> collection = new List<T>(); public T this[int index] { get { return collection[index]; } } public void Add(T p) { collection.Add(p); } #region IEnumerable<T> 成员 public IEnumerator<T> GetEnumerator() { return new CommEnumerator<T>(collection); } #endregion #region IEnumerable 成员 System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return new CommEnumerator<T>(collection); } #endregion private class CommEnumerator<E> : System.Collections.Generic.IEnumerator<E> { List<E> collection; int position = -1; public CommEnumerator(List<E> theCollection) { this.collection = theCollection; } #region IEnumerator 成员 public E Current { get { return this.collection[position]; } } public bool MoveNext() { if (position < collection.Count - 1) { position++; return true; } else { return false; } } public void Reset() { this.position = -1; } #endregion #region IDisposable 成员 public void Dispose() { } #endregion #region IEnumerator 成员 object System.Collections.IEnumerator.Current { get { return collection[position]; } } #endregion } } #endregion #region 3.自定义能返回IEnumerator的GetEnumerator()方法(一般都用此方式实现) public class MyselfForeach<T> { List<T> collection = new List<T>(); public T this[int index] { get { return collection[index]; } } public void Add(T item) { collection.Add(item); } public System.Collections.Generic.IEnumerator<T> GetEnumerator() { foreach (T t in collection) { yield return t; } } //public System.Collections.IEnumerator GetEnumerator() //{ // foreach (T t in collection) // { // yield return t; // } //} } #endregion