我们写一些实体类的时候,总希望它们可以进行foreach遍历,但是默认的是不能进行foreach遍历。
假如我有一个汽车类和一个汽车工厂类见下面代码:
public class Car
{
private string _name;
public string Name
{
get
{
return _name;
}
set
{
_name = value;
}
}
public Car(string name)
{
_name = name;
}
}
public class CarFactory
{
private Car[] carArry;
public CarFactory()
{
carArry = new Car[2];
carArry[0] = new Car("carA");
carArry[1] = new Car("carB");
}
}
{
private string _name;
public string Name
{
get
{
return _name;
}
set
{
_name = value;
}
}
public Car(string name)
{
_name = name;
}
}
public class CarFactory
{
private Car[] carArry;
public CarFactory()
{
carArry = new Car[2];
carArry[0] = new Car("carA");
carArry[1] = new Car("carB");
}
}
然后在客户端进行使用
static void Main(string[] args)
{
CarFactory carFactory = new CarFactory();
foreach (Car c in carFactory)
{
Console.WriteLine(c.Name);
}
}
{
CarFactory carFactory = new CarFactory();
foreach (Car c in carFactory)
{
Console.WriteLine(c.Name);
}
}
现在你会发现编译器通不过,会提示一个这样的错误:
“错误 1 “ConsoleApplication1.CarFactory”不包含“GetEnumerator”的公共定义,因此 foreach 语句不能作用于“ConsoleApplication1.CarFactory”类型的变量 D:\VS2008\Test\ConsoleApplication1\ConsoleApplication1\Program.cs 14 13 ConsoleApplication1”
它提示说我们的类中没有实现GetEnumerator方法。
这时我们只需要把我们的CarFactory类实现IEnumerable接口就可以了,见下面代码:
public class CarFactory:IEnumerable
{
private Car[] carArry;
public CarFactory()
{
carArry = new Car[2];
carArry[0] = new Car("carA");
carArry[1] = new Car("carB");
}
#region IEnumerable 成员
public IEnumerator GetEnumerator()
{
return carArry.GetEnumerator();
}
#endregion
}
{
private Car[] carArry;
public CarFactory()
{
carArry = new Car[2];
carArry[0] = new Car("carA");
carArry[1] = new Car("carB");
}
#region IEnumerable 成员
public IEnumerator GetEnumerator()
{
return carArry.GetEnumerator();
}
#endregion
}
参考书:《C#与.Net3.0高级程序设计》