C# yield Statement

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版
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值