集合概述

我们知道,数组是System.Array类的一个实例。但是,数组有很大的缺点,就是需要指定大小,也不能添加,插入,删除元素。因此,在.NET中引入了集合的概念,所有的集合类都存放在System.Collections命名空间下。

所有的集合必须实现 System.Collections.IEnumerable接口,该接口的原型如下:

1 interface IEnumerable 
2 {
3   IEnumerator GetEnumerator();
4 }

 System.Collections.IEnumerator也是一个基本的.NET关于集合的接口,它的原型如下:

1 interface IEnumerator
2 {
3     object Current { get; }
4     bool MoveNext();
5     void Reset();
6 }

两种遍历集合的方式:

1)使用枚举器

1 IEnumerator enumertor = MySet.GetEnumerator();
2 string element;
3 enumertor.MoveNext();
4 while ((element=enumertor.Current)!=null)
5 {
6     //do something with element
7     
8     enumertor.MoveNext();
9 }

2)使用foreach循环

1 foreach (string element in MySet)
2 {
3     //do something with element
4 }
原文地址:https://www.cnblogs.com/davidgu/p/1507678.html