C#1.0 通过使用Foreach语句使得迭代集合(collection)变得简单,在C#1.0中,还需要创建枚举器(Enumerator.)的工作要做,为此、C#2.0新增了yield语句、很方便的创建枚举器(Enumerator.)。yield 返回一个集合的元素、并把当前位置指向下一个元素、它打破了迭代顺序。接下来的例子展示了使用yield语句实现了一个简单的集合,类HelloCollection 包含方法 GetEnumerator(),实现GetEnumerator()方法包含两条yield返回语句"Hello"和"World"。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace Console4
{
public class HelloConnection
{
public IEnumerator GetEnumerator()
{
yield return "Hello";
yield return "World";
}
}
}
说明:一个包含yield语句的方法或属性都可被看作一个迭代块,一个迭代块必须定义一个返回一个IEnumerator 或者 IEnumerable 接口,这模块可能包含多 个 yield语句或yield跳出语句,但是只返回(return)是不被允许的.
现在可以用Foreach语句迭代包含类HelloCollection的集合了
public class Program
{
HelloCollection helloCollection =new HelloCollection();
foreach (string s in helloCollection)
{
Console.WriteLine(s);
}
}
推荐博客: RyanDoc数据字典 For SqlServer版 RyanCoder代码生成器 For SqlServer版