C#中的yield return
C#语法中有个特别的关键字yield, 它是干什么用的呢?
来看看专业的解释:
yield 是在迭代器块中用于向枚举数对象提供值或发出迭代结束信号。它的形式为下列之一:
yield return <expression>;
yield break
看如下例子:
1 1 public class CustomCollection :IEnumerable { 2 2 3 3 public static void Main (string[] args) 4 4 { 5 5 CustomCollection cc = new CustomCollection (); 6 6 7 7 foreach (String word in cc) { 8 8 Console.WriteLine ("word:" +word); 9 9 } 10 10 } 11 11 12 12 public IEnumerator GetEnumerator(){ 13 13 14 14 yield return "Hello"; 15 15 yield return "Boys"; 16 16 yield return "And"; 17 17 yield return "Girls"; 18 18 //return new HelloBoyGirls(); 19 19 20 20 } 21 21 } 22 22 23 23 // public class HelloBoyGirls: IEnumerator { 24 24 // private int cusor = -1; 25 25 // private String[] words = {"Hello", "Boys", "And", "Girls"}; 26 26 // 27 27 // public bool MoveNext () 28 28 // { 29 29 // cusor++; 30 30 // return cusor < words.Length; 31 31 // } 32 32 // 33 33 // public void Reset () 34 34 // { 35 35 // cusor = 0; 36 36 // } 37 37 // 38 38 // public object Current { 39 39 // get { 40 40 // return words [cusor]; 41 41 // } 42 42 // } 43 43 // }