可以通过实现 IEnumerable<T> 或 IEnumerable 接口定义集合。 有关其他信息,请参见 枚举集合 和 如何:使用 foreach 访问集合类(C# 编程指南)。
虽然您可以定义自定义集合,但通常最好使用包括在 .NET Framework(本主题前面的集合类型中有所介绍)中的集合。
下面的示例定义名为 AllColors 的客户集合类。 该选件类实现了 IEnumerable 接口,需执行 GetEnumerator 方法。
GetEnumerator 方法返回 ColorEnumerator 类的一个实例。 ColorEnumerator 实现 IEnumerator 接口,这需要首先实现 Current 属性、MoveNext 方法和 Reset 方法。
private void ListColors() {
var colors = new AllColors();foreach(Color theColor in colors){
Console.WriteLine(theColor.name+" ");
}
Console.ReadKey();
}
public class AllColors : System.Collections.IEnumerable {
Color[] _colors = {new Color(){name = "red"},new Color(){name = "blue"},new Color(){name = "green"}} ;
public System.Collections.IEnumerator GetEnumerator() {
return new ColorEnumerator(_colors);
}
}
private class ColorEnumerator : System.Collections.IEnumerator {
private Color[] _colors;
private int _position = -1;
public ColorEnumerator(Color[] colors) {
_colors = colors;
}
Object System.Collections.IEnumerator.Current {
get { return _colors[_position];}
}
bool System.Collections.IEnumerator.MoveNext() {
_position++;
return (_position <_colors.Length);
}
void System.Collections.IEnumerator.Reset() {
_position = -1;
}
}
public class Color {
public string name { get; set; }
}