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);
            }
        }
    }

  • 相关阅读:
    ElasticSearch原理
    redis master配置了密码进行主从同步
    redis sentinel 高可用(HA)方案部署,及python应用示例
    Linux Redis集群搭建与集群客户端实现
    字符串倒序
    单链表反转
    【python】面试常考数据结构算法
    面试中的排序算法总结
    Memcached 真的过时了吗?
    Activity生命周期
  • 原文地址:https://www.cnblogs.com/voidobject/p/3975496.html
Copyright © 2011-2022 走看看