public class Person
{
private string[] friends = { "asf", "ewrqwe", "ddd", "eeee" };
public string name { get; set; } public int age { get; set; }
//这是第一种方法
public IEnumerable ForEach()
{
for (int i = ; i < friends.Length; i++)
{
yield return friends[i];
}
}
}
调用
class Program
{
static void Main(string[] args)
{
Person p = new Person(); foreach (var item in p.ForEach())
{
Console.WriteLine(item);
} Console.Read();
}
}
第二种 方法
class Program
{
static void Main(string[] args)
{
Person p = new Person(); foreach (var item in p)
{
Console.WriteLine(item);
} Console.Read();
}
} public class Person
{
private string[] friends = { "asf", "ewrqwe", "ddd", "eeee" };
public string name { get; set; } public int age { get; set; } //这是第二种
////当返回值类型是IEnumerator时,
//编译器帮我们生成了一个“枚举器”类,
//即:一个实现了IEnumerator接口的类型。
public IEnumerator GetEnumerator()
{
for (int i = ; i < friends.Length; i++)
{
yield return friends[i];
}
}
}
第三种 方法 自己生产枚举器
class Program
{
static void Main(string[] args)
{
Person p = new Person(); foreach (var item in p)
{
Console.WriteLine(item);
} Console.Read();
}
} public class Person
{
private string[] friends = { "asf", "ewrqwe", "ddd", "eeee" };
public string name { get; set; } public int age { get; set; } //这是第二种
////当返回值类型是IEnumerator时,
//编译器帮我们生成了一个“枚举器”类,
//即:一个实现了IEnumerator接口的类型。
public IEnumerator GetEnumerator()
{
return new PersonEnumerator(friends);
}
} //枚举器
public class PersonEnumerator : IEnumerator
{
private string[] frends;
//使用构造函数 传值
public PersonEnumerator(string[] fs)
{
frends = fs;
}
private int index = -; public object Current
{
get
{
if (index >= && index < frends.Length)
{
return frends[index];
}
else
{
throw new NotImplementedException();
}
}
} public bool MoveNext()
{
if (index + < frends.Length)
{
index++;
return true;
}
return false;
} public void Reset()
{
index = -; } }