---
title: "基于Visual Studio2010讲解C#4.0语法(4)--使用yield迭代器"
author: "winzenghua"
date: "2010-05-12T16:32:00Z"
tags: []
slug: "visual-studio2010-c-4-0-4-yield"
draft: false
lastmod: "2010-05-12T16:32:00Z"
id: 948062
url: "https://java4gis.iteye.com/blog/948062"
---

在**yield**[迭代器](http://msdn.microsoft.com/en-us/dscyy5s0%28zh-cn,VS.90%29.aspx)块中用于向枚举数对象提供值或发出迭代结束信号。它的形式为下列之一：

[]()

```
yield return <expression>;
yield break;
```

计算表达式并以枚举数对象值的形式返回；*expression* 必须可以隐式转换为迭代器的 yield 类型。

**yield** 语句只能出现在 **iterator** 块中，该块可用作方法、运算符或访问器的体。这类方法、运算符或访问器的体受以下约束的控制：

- 不允许不安全块。
- 方法、运算符或访问器的参数不能是 [ref](http://msdn.microsoft.com/en-us/14akc2c7%28zh-cn,VS.90%29.aspx) 或 [out](http://msdn.microsoft.com/en-us/t3c3bfhx%28zh-cn,VS.90%29.aspx)。

**yield** 语句不能出现在匿名方法中。有关更多信息，请参见 [匿名方法（C# 编程指南）](http://msdn.microsoft.com/en-us/0yw3tz5k%28zh-cn,VS.90%29.aspx)。

当和 *expression* 一起使用时，**yield return** 语句不能出现在 **catch** 块中或含有一个或多个 **catch** 子句的 **try** 块中。

在下面的示例中，迭代器块（这里是方法 Power(int number, int power)）中使用了 **yield** 语句。当调用 **Power** 方法时，它返回一个包含数字幂的可枚举对象。注意 **Power** 方法的返回类型是 **IEnumerable**（一种迭代器接口类型）。

比如下面的例子：

public class List  
{  
//using System.Collections;  
public static IEnumerable Power(int number, int exponent)  
{  
int counter = 0;  
int result = 1;  
while (counter++ &lt; exponent)  
{  
result = result * number;  
yield return result;  
}  
}

static void Main()  
{  
// Display powers of 2 up to the exponent 8:  
foreach (int i in Power(2, 8))  
{  
Console.Write("{0} ", i);  
}  
}  
}  
/*  
Output:  
2 4 8 16

我们来看一个实例：

首先打开Visual Studio2010创建一个基于C#的ConsoleApplication工程Yield：

![](http://hi.csdn.net/attachment/201005/12/5923932_12736761693N09.png)

然后打开Yield.cs文件加入下列代码：

按下F5开始调试，运行界面如下：

![](http://hi.csdn.net/attachment/201005/12/5923932_1273676170ZDKx.png)