参考 李志. Learning hard C#学习笔记 (图灵原创) (p. 119). 人民邮电出版社. Kindle 版本.
1 public class Friend 2 { 3 string name; 4 public string Name 5 { 6 get 7 { 8 return name; 9 } 10 set 11 { 12 name = value; 13 } 14 } 15 public Friend(string name) 16 { 17 this.name = name; 18 } 19 20 } 21 public class Friends : IEnumerable 22 { 23 List<Friend> fname_list; 24 public Friends(List<string> nlist) 25 { 26 fname_list = new List<Friend>(); 27 foreach (var item in nlist) 28 { 29 fname_list.Add(new Friend(item)); 30 } 31 } 32 public IEnumerator GetEnumerator() 33 { 34 for (int i = 0; i < fname_list.Count; i++) 35 { 36 yield return fname_list[i]; 37 } 38 } 39 } 40 41 class Program 42 { 43 static void Main(string[] args) 44 { 45 Friends tfs = new Friends(new List<string>() { "aa","bb","cc" }); 46 47 foreach (Friend item in tfs) 48 { 49 Console.WriteLine(item.Name); 50 } 51 52 Console.ReadKey(); 53 } 54 }