zoukankan      html  css  js  c++  java
  • C# 自定义类型实现foreach 迭代

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Collections;
    namespace Foreach
    {
        class Program
        {
            static void Main(string[] args)
            {
                person[] persons = new person[]{
                    new person("aaa",20),
                    new person("bbb",21),
                    new person("ccc",22),
                };

                People peopleList = new People(persons);
                foreach (var item in peopleList)
                {
                   
                    Console.WriteLine(item);
                }
                Console.ReadLine();
                //person p = new person("aaa", 12);  //调用了重写的函数方法
                //Console.WriteLine(p.ToString());
            }
        }
        public class person
        {
            string Name;
            int Age;
            public person(string name,int age)
            {
                Name = name;
                this.Age = age;
            }
            public override string ToString()
                //重写ToString()方法
            {
                return "Name:" + this.Name + "\tAge:" + this.Age;
            }

        }

        public class PeopleEnum : System.Collections.IEnumerator
        {
            private person[] _people;    //要控制的people
            int postion = -1;
            public PeopleEnum(person[] list)
            {
                _people = list;
            }
            public object Current
            {
                //get { throw new NotImplementedException(); }
                get {
                    return _people[postion];
                }
            }

            public bool MoveNext()
            {
                //throw new NotImplementedException();
                postion++;
                return (postion < _people.Length);
            }

            public void Reset()
            {
                //throw new NotImplementedException();
                postion = -1;
            }
        }
        public class People : IEnumerable
        {
            private person[] _people;
            public People(person[] pArray)
            {
                _people = new person[pArray.Length];
                for (int i = 0; i < pArray.Length; i++)
                {
                    _people[i] = pArray[i];
                }
            }
            public IEnumerator GetEnumerator()
            {
                //throw new NotImplementedException();
                return new PeopleEnum(_people);
            }
        }
    }

  • 相关阅读:
    FZU OJ 1056 :扫雷游戏
    HPU 1166: 阶乘问题(一)
    常用的一些模板
    PAT天梯:L1-019. 谁先倒
    HPU 1437: 王小二的求值问题
    《编程珠玑》阅读小记(7) — 代码调优与节省空间
    《编程珠玑》阅读小记(6) — 算法设计技术
    《编程珠玑》阅读小记(5) — 编程小事
    《编程珠玑》阅读小记(4) — 编写正确的程序
    《C/C++专项练习》— (1)
  • 原文地址:https://www.cnblogs.com/voidobject/p/3975496.html
Copyright © 2011-2022 走看看