C# 什么时候需要实现IEnumerator,IEnumerable这2个接口?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Collections;
using System.Data.Common;
using System.Data;
using System.Security.Util;
using System.Text.RegularExpressions;

namespace Demo
{
    class Program
    {
        static void Main(string[] args)
        {
            Person[] ps = { new Person("a", 1), new Person("b", 2), new Person("c", 3) };
            People p = new People(ps);
            foreach (Person item in p)
            {
                Console.WriteLine("name={0},age={1}",item.Name,item.Age);
            }
            Console.Read();
        }
        
    }
    class Person
    {
        public string Name;
        public int Age;
        public Person(string name, int age)
        {
            Name = name;
            Age = age;
        }
    }
    class PersonEnum : IEnumerator
    {
        Person []ps;
        public PersonEnum(Person[]ps)
        {
            this.ps=ps;
        }
        int position = -1;
        public void Reset (){  position=-1;}

        public bool MoveNext() { ++position; return position < ps.Length; }

        public object Current { get { return ps[position];} }
    }
    class People:IEnumerable
    {
        Person[] ps;
        public People(Person[]ps)
        {
            this.ps = ps;
        }
        public IEnumerator GetEnumerator()
        {
            return new PersonEnum(ps);
        }
    }

}

上边例子中,如果将Main中的代码换成下边这样子也能实现foreach啊,为什么要像上面这样写呢?

Person[] ps = { new Person("a", 1), new Person("b", 2), new Person("c", 3) };

            foreach (Person item in ps)
            {
                Console.WriteLine("name={0},age={1}",item.Name,item.Age);
            }
            Console.Read();
慕码人8056858
浏览 389回答 4
4回答

慕森王

用到数组或者集合的时候都要实现

慕尼黑8549860

本质就是对设计模式中迭代器模式的一个实现,建议看下这个模式就知道背后的原理了
打开App,查看更多内容
随时随地看视频慕课网APP