foreach语句,就是调用GetEnumerator()方法,得到一个数组的枚举器,然后在while循环中判断MoveNext(),如果为true,就可以用Current属性来访问数组中的元素。
根据网上的例子,自己打的代码。IEnumerable接口和IEnumerator接口都在System。Collections里。
using System;
using System.Collections;
namespace Simple
{
public class MainEntryPoint
{
static int Main(string[] args)
{
Person[] pArray = new Person[]
{
new Person("July","Wu"),
new Person("Joyn","Wu"),
new Person("John","Wu")
};
foreach(Person i in pArray)
{
Console.WriteLine(i);
}
return 0;
}
}
//用户类
public class Person
{
public string firstName;
public string lastName;
public Person(string firstName, string lastName)
{
this.firstName = firstName;
this.lastName = lastName;
}
public override string ToString()
{
return firstName+" "+lastName;
}
}
版权声明:本文为july_yeye原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。