C#中的yield关键字的使用方法介绍

来源:互联网 发布:js 对象 key 变量 编辑:程序博客网 时间:2024/05/21 15:44

yield这个关键字是和迭代器挂钩的,而且是与return一起以yield return的形式合用的,用来返回迭代器中的条目。
yield不能单独放在try-catch块中,如果try中有yield那么,这个try块后面不许跟着finally块;也不能出现在匿名方法中,所以,看起来yield似乎并不常用,但是也不是不用。我前面有一个关于迭代器的例子《C#中的迭代器基础》中就用到了。可以参考一下那个例子,但是这里要再说的一点是我后来看到的,yield是跟return一起使用的,形式为yield return xxx,一般来说单独的return在每个方法中只能存在一个。而yield则不同的是,可以出现连续多个。
迭代器,是一个连续的集合,出现多个yield return其实就是将这多个的yield return元素按照出现的顺序存储在迭代器的集合中而已。形如下面的形式:
代码如下:

 public class CityCollection : IEnumerable<string>  {      string[] _Items = new string[] { "黑龙江", "吉林", "辽宁", "山东", "山西", "陕西", "河北", "河南", "湖南", "湖北", "四川", "广西", "云南", "其他" };      IEnumerator<string> IEnumerable<string>.GetEnumerator()      {          for (int i = 0; i < _Items.Length; i++)          {              yield return _Items[i];              yield return string.Format("Index:{0}", i);         }     }     IEnumerator IEnumerable.GetEnumerator()     {         for (int i = 0; i < _Items.Length; i++)         {             yield return _Items[i];         }     } }

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

  黑龙江  Index:0  吉林  Index:1  辽宁  Index:2  山东  Index:3  山西 Index:4 陕西 Index:5 河北 Index:6 河南 Index:7 湖南 Index:8 湖北 Index:9 四川 Index:10 广西 Index:11 云南 Index:12 其他 Index:13

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

0 0