码迷,mamicode.com
首页 > 编程语言 > 详细

C#中的yield return与Unity中的Coroutine(协程)

时间:2016-03-13 19:38:59      阅读:225      评论:0      收藏:0      [点我收藏+]

标签:

C#中的yield return

C#语法中有个特别的关键字yield, 它是干什么用的呢?

来看看专业的解释:

yield 是在迭代器块中用于向枚举数对象提供值或发出迭代结束信号。它的形式为下列之一:
yield return <expression>;
yield break

 

看如下例子:

 1     public class CustomCollection :IEnumerable {
 2         
 3         public static void Main (string[] args)
 4         {
 5             CustomCollection cc = new CustomCollection ();
 6 
 7             foreach (String word in cc) {
 8                 Console.WriteLine ("word:" +word);
 9             }
10         }
11 
12         public IEnumerator GetEnumerator(){
13 
14             yield return "Hello";
15             yield return "Boys";
16             yield return "And";
17             yield return "Girls";
18             //return new HelloBoyGirls();
19 
20         }
21     }
22 
23 //    public class HelloBoyGirls: IEnumerator {
24 //        private int cusor = -1;
25 //        private String[] words = {"Hello", "Boys", "And", "Girls"};
26 //        
27 //        public bool MoveNext ()
28 //        {
29 //            cusor++;
30 //            return cusor < words.Length;
31 //        }
32 //
33 //        public void Reset ()
34 //        {
35 //            cusor = 0;
36 //        }
37 //
38 //        public object Current {
39 //            get {
40 //                return words [cusor];
41 //            }
42 //        }
43 //    }

上面的例子是实现了一个自定义的迭代器;实现可迭代(可以用foreach)的数据集合,必须实现GetEmumerator()方法,返回实现了IEmumerator的对象实例。

完成这个, 有两种方法,一种是用上面注释掉的代码,一种是用yield return. yield return 需要配合IEmumerator进行使用, 在外部foreach循环中,它会执行GetEmumerator()方法,遇到yield return, 做了如下两件事情:

1.记录下当前执行到的代码位置

2. 将代码控制权返回到外部, yield return 后面的值, 作为迭代的当前值。

当执行下一个循环, 从刚才记录的代码位置后面, 开始继续执行代码。

简单地说, yield return 就是实现IEmumerator的超级简化版, 是不是很简单?

 

 

C#中的yield return与Unity中的Coroutine(协程)

标签:

原文地址:http://www.cnblogs.com/vivid-stanley/p/5272736.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!