C#中的yield关键字的一个用法

yield这个关键字是和迭代器挂钩的,而且是与return一起以yield return的形式合用的,用来返回迭代器中的条目。

yield不能单独放在try-catch块中,如果try中有yield那么,这个try块后面不许跟着finally块;也不能出现在匿名方法中,所以,看起来yield似乎并不常用,但是也不是不用。我前面有一个关于迭代器的例子《C#中的迭代器基础》中就用到了。可以参考一下那个例子,但是这里要再说的一点是我后来看到的,yield是跟return一起使用的,形式为yield return xxx,一般来说单独的return在每个方法中只能存在一个。而yield则不同的是,可以出现连续多个。

迭代器,是一个连续的集合,出现多个yield return其实就是将这多个的yield return元素按照出现的顺序存储在迭代器的集合中而已。形如下面的形式:

 1 public class CityCollection : IEnumerable<string>
2 {
3 string[] _Items = new string[] { "黑龙江", "吉林", "辽宁", "山东", "山西", "陕西", "河北", "河南", "湖南", "湖北", "四川", "广西", "云南", "其他" };
4 IEnumerator<string> IEnumerable<string>.GetEnumerator()
5 {
6 for (int i = 0; i < _Items.Length; i++)
7 {
8 yield return _Items[i];
9 yield return string.Format("Index:{0}", i);
10 }
11 }
12 IEnumerator IEnumerable.GetEnumerator()
13 {
14 for (int i = 0; i < _Items.Length; i++)
15 {
16 yield return _Items[i];
17 }
18 }
19 }

而返回的迭代结果就是这样的:

 1 黑龙江
2 Index:0
3 吉林
4 Index:1
5 辽宁
6 Index:2
7 山东
8 Index:3
9 山西
10 Index:4
11 陕西
12 Index:5
13 河北
14 Index:6
15 河南
16 Index:7
17 湖南
18 Index:8
19 湖北
20 Index:9
21 四川
22 Index:10
23 广西
24 Index:11
25 云南
26 Index:12
27 其他
28 Index:13

每一条yield return都是迭代器中的一个元素。

更多内容请查看:http://luacloud.com/2011/csharp-yield-return.html

posted @ 2011-12-01 16:09  ojdev  阅读(494)  评论(0编辑  收藏  举报