鸟语天空
IEnumerable与IEnumerator
post by:追风剑情 2019-7-17 10:36

一、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

评论:
发表评论:
昵称

邮件地址 (选填)

个人主页 (选填)

内容