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]; } } }