IEnumerable与IEnumerator

作者:追风剑情 发布于:2019-7-17 10:36 分类:C#

一、IEnumerable与IEnumerator之间的关系

  1. namespace System.Collections
  2. {
  3. public interface IEnumerable
  4. {
  5. IEnumerator GetEnumerator();
  6. }
  7. }

  1. namespace System.Collections
  2. {
  3. public interface IEnumerator
  4. {
  5. object Current { get; }
  6. bool MoveNext();
  7. void Reset();
  8. }
  9. }


示例

  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Text;
  6.  
  7. namespace Test
  8. {
  9. class Program
  10. {
  11. static void Main(string[] args)
  12. {
  13. List<Student> list = new List<Student>()
  14. {
  15. new Student() { name = "aaa" },
  16. new Student() { name = "bbb" }
  17. };
  18.  
  19. //因为List实例了IEnumerable接口,可以用foreach遍历
  20. foreach(var st in list)
  21. {
  22. Console.WriteLine(st.name);
  23. }
  24.  
  25. //下面的代码与foreach等价
  26. //IEnumerable接口中定义了GetEnumerator()方法
  27. IEnumerator enumerator = list.GetEnumerator();
  28. while (enumerator.MoveNext())
  29. {
  30. Student st = enumerator.Current as Student;
  31. Console.WriteLine(st.name);
  32. }
  33.  
  34. Console.ReadLine();
  35. }
  36. }
  37.  
  38. public class Student
  39. {
  40. public string name;
  41. }
  42. }


运行测试

1111.png

标签: C#

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号