IEnumerable与IEnumerator

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

一、IEnumerable与IEnumerator之间的关系

namespace System.Collections
{
    public interface IEnumerable
    {
        IEnumerator GetEnumerator();
    }
}

namespace System.Collections
{
    public interface IEnumerator
    {
        object Current { get; }
        bool MoveNext();
        void Reset();
    }
}


示例

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            List<Student> list = new List<Student>()
            {
                new Student() { name = "aaa" },
                new Student() { name = "bbb" }
            };

            //因为List实例了IEnumerable接口,可以用foreach遍历
            foreach(var st in  list)
            {
                Console.WriteLine(st.name);
            }

            //下面的代码与foreach等价
            //IEnumerable接口中定义了GetEnumerator()方法
            IEnumerator enumerator = list.GetEnumerator();
            while (enumerator.MoveNext())
            {
                Student st = enumerator.Current as Student;
                Console.WriteLine(st.name);
            }

            Console.ReadLine();
        }
    }

    public class Student
    {
        public string name;
    }
}


运行测试

1111.png

标签: C#

Powered by emlog  蜀ICP备18021003号   sitemap

川公网安备 51019002001593号