1 public class Person 2 { 3 private string[] friends = { "asf", "ewrqwe", "ddd", "eeee" }; 4 public string name { get; set; } 5 6 public int age { get; set; } 7 //这是第一种方法 8 public IEnumerable ForEach() 9 { 10 for (int i = 0; i < friends.Length; i++) 11 { 12 yield return friends[i]; 13 } 14 } 15 }
调用
1 class Program 2 { 3 static void Main(string[] args) 4 { 5 Person p = new Person(); 6 7 foreach (var item in p.ForEach()) 8 { 9 Console.WriteLine(item); 10 } 11 12 Console.Read(); 13 } 14 }
第二种 方法
class Program { static void Main(string[] args) { Person p = new Person(); foreach (var item in p) { Console.WriteLine(item); } Console.Read(); } } public class Person { private string[] friends = { "asf", "ewrqwe", "ddd", "eeee" }; public string name { get; set; } public int age { get; set; } //这是第二种 ////当返回值类型是IEnumerator时, //编译器帮我们生成了一个“枚举器”类, //即:一个实现了IEnumerator接口的类型。 public IEnumerator GetEnumerator() { for (int i = 0; i < friends.Length; i++) { yield return friends[i]; } } }
第三种 方法 自己生产枚举器
1 class Program 2 { 3 static void Main(string[] args) 4 { 5 Person p = new Person(); 6 7 foreach (var item in p) 8 { 9 Console.WriteLine(item); 10 } 11 12 Console.Read(); 13 } 14 } 15 16 public class Person 17 { 18 private string[] friends = { "asf", "ewrqwe", "ddd", "eeee" }; 19 public string name { get; set; } 20 21 public int age { get; set; } 22 23 //这是第二种 24 ////当返回值类型是IEnumerator时, 25 //编译器帮我们生成了一个“枚举器”类, 26 //即:一个实现了IEnumerator接口的类型。 27 public IEnumerator GetEnumerator() 28 { 29 return new PersonEnumerator(friends); 30 } 31 } 32 33 34 //枚举器 35 public class PersonEnumerator : IEnumerator 36 { 37 private string[] frends; 38 //使用构造函数 传值 39 public PersonEnumerator(string[] fs) 40 { 41 frends = fs; 42 } 43 private int index = -1; 44 45 46 public object Current 47 { 48 get 49 { 50 if (index >= 0 && index < frends.Length) 51 { 52 return frends[index]; 53 } 54 else 55 { 56 throw new NotImplementedException(); 57 } 58 } 59 } 60 61 public bool MoveNext() 62 { 63 if (index + 1 < frends.Length) 64 { 65 index++; 66 return true; 67 } 68 return false; 69 } 70 71 public void Reset() 72 { 73 index = -1; 74 75 } 76 77 78 }