分享

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

 球球圆圆豆豆 2015-12-09
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();

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多