• 实现IEnumable以迭代对象示例


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

    namespace StaticTest
    {
        class Person           //被迭代对象
        {
            public string fName;
            public string lName;
            public Person(string fName,string lName)
            {
                this.fName = fName;
                this.lName = lName;
            }
        }

        class People:IEnumerable      //迭代对象的容器
        {
            private Person[] _people;
            public People(Person[] person)
            {
                _people = new Person[person.Length];
                for (int i = 0; i < person.Length; i++)
                {
                    _people[i]=person[i];
                }
            }
            IEnumerator IEnumerable.GetEnumerator()
            {
                return new PeopleEnum(_people);
            }
        }
        class PeopleEnum : IEnumerator //迭代器
        {
            int position = -1;
            public Person[] _person;
            public PeopleEnum(Person[] person)
            {
                _person = person;
            }
            public bool MoveNext()
            {
                position++;
                return (position < _person.Length);
            }
            public void Reset()
            {
                position = -1;
            }
            public object Current
            {
                get
                {
                    try
                    {
                        return _person[position];
                    }
                    catch (IndexOutOfRangeException)
                    {
                        throw new InvalidOperationException();
                    }
                }

            }
        } 
        class Program
        {
            static void Main(string[] args)
            {
                Person[] person = {
                                  new Person("张","三"),new Person("李","四"),new Person("王","五")
                                  };
                People peo = new People(person);
                foreach (Person pp in peo)
                {
                    Console.WriteLine("fName:"+pp.fName+",lName:"+pp.lName);
                }
            }
        }
    }

  • 相关阅读:
    exit()和_exit()函数(转)
    C语言struct内存占用问题 (转)
    C语言中memset函数(转)
    STDIN_FILENO与stdin区别(转)
    stderr,strerror,errno,perror,论坛大神的回答!
    C++ 函数模版
    C++ 内置函数
    offsetof
    LockSupportDemo
    读写锁,await和signa
  • 原文地址:https://www.cnblogs.com/liancs/p/3879358.html
Copyright © 2020-2023  润新知