C# 中对 IEnumerable IEnumerator yield 的理解

    前段时间 用C# 来写 Unity3D(一款游戏引擎) 中的行为脚本. 其中有一个非常重要的概念是"协同程序", 我的理解就是用来完成一系列的有先后顺序的操作.比如做为一个动画后.等上一段时间 再进行下一步操作. 它的好处在于 可以不影响当前的时间线类似于单开一个线程一样的来完成这个工作.

    在Unity3D中完成协同程序的操作是这样的.用StartCoroutine(method());的方法来调用,method方法必须返回一个IEnumerator类型的方法:IEnumerator Fun() {yield return ...}. 

    所以想了解一下  IEnumerable IEnumerator yield  这几个关键字.在C#中的功能都是什么? 通过在网上的资料了解到 就是为了让类可以用foreach来遍历. 

  想用foreach遍历类,类主要是需要有返回IEnumerator 类型的方法 . 不一定继承IEnumerable接口(虽然不在代码中明确的写上实现 IEnumerable 也是没有问题的. 但写上还是规范些. 别人能看懂.鼓励写上.).. 只有这个方法即可. 而这个方法的实现可以有两种情况. 一种是自己去实现接口中的方法 Current MoveNext() Reset(),还有一种就是用yield return .. 方法 . 他会自动的产生IEnumerator 的那三个方法. 所以非常的方便实用..:

 

View Code
 1 using System;
2 using System.Collections;
3
4 /// <summary>
5 /// 总结:如果想使用foreach 类必须实现IEnumerable.. 而它又需要IEnumerator. 这个可以用
6 /// yield 来实现, 也可以自己实现IEnumerator 接口
7 /// </summary>
8
9 class Test : IEnumerable //使用 yield return 来自动的生成 IEnumerator 方法
10 {
11 public IEnumerator GetEnumerator()
12 {
13 yield return "hello";
14 yield return "world";
15 yield return "who are you?";
16 }
17 }
18 class Test2 : IEnumerator,IEnumerable //自己实现 IEnumerator 方法,
19 {
20 string[] ss = {"I am Test2","haha","yehh","Movie"};
21 int i = -1; //为了在一开始调用Current 时不报错 所以这个值给成-1. 因为在调用Current前会调用 MoveNext 方法
22
23 public Object Current
24 {
25 get
26 {
27 return ss[i];
28 }
29 }
30 public bool MoveNext()
31 {
32 if (i<ss.Length -1)
33 {
34 i = i + 1;
35 return true;
36 }
37 else
38 return false;
39 }
40 public void Reset()
41 {
42 i = -1;
43 }
44 public IEnumerator GetEnumerator()
45 {
46 return(this);
47 }
48 }
49 class main
50 {
51 public static void Main()
52 {
53 Test t = new Test();
54 foreach(string s in t)
55 Console.WriteLine(s);
56
57 Test2 t2 = new Test2();
58 foreach(string s in t2)
59 Console.WriteLine(s);
60 }
61 }



posted @ 2011-12-29 22:20  easyfrog  阅读(3136)  评论(2编辑  收藏  举报