通过IEnumerable接口遍历数据

使用IEnumerable接口遍历数据,这在项目中会经常的用到,这个类型呢主要是一个枚举器。

1.首先需要让该类型实现一个名字叫IEnumerable的接口,实现该接口的主要目的是为了让当前类型中增加一个名字叫GetEnumerator()的方法。

复制代码
复制代码
public class Person : IEnumerable
    {
        private string[] Friends = new string[] { "张三", "李四", "王五", "赵六" };

        public string Name
        {
            get;
            set;
        }
        public int Age
        {
            get;
            set;
        }
        public string Email
        {
            get;
            set;
        }

        #region IEnumerable 成员

        //这个方法的作用就是返回一个“枚举器”
        public IEnumerator GetEnumerator()
        {
            return new PersonEnumerator(this.Friends);
        }

        #endregion
    }
复制代码
复制代码

2.希望一个类型被枚举遍历,就是要实现一个枚举器方法

复制代码
复制代码
public class PersonEnumerator : IEnumerator
    {
        public PersonEnumerator(string[] fs)
        {
            _friends = fs;
        }
        private string[] _friends;

        //一般下标都是一开始指向了第一条的前一条。第一条是0
        private int index = -1;


        #region IEnumerator 成员

        public object Current
        {
            get
            {
                if (index >= 0 && index < _friends.Length)  //下标有范围
                {
                    return _friends[index];
                }
                else
                {
                    throw new IndexOutOfRangeException();
                }
            }
        }
       
        public bool MoveNext()
        {
            if (index + 1 < _friends.Length)     //下标有范围
            {
                index++;
                return true;
            }
            return false;
        }

        public void Reset()
        {
            index = -1;
        }

        #endregion
    }
复制代码
复制代码

3.然后进行遍历,这里呢可以调用自己封装的MoveNext方法去找数组元素

复制代码
复制代码
 Person p = new Person();

            IEnumerator etor = p.GetEnumerator();
            while (etor.MoveNext())
            {
                Console.WriteLine(etor.Current.ToString());
            }
复制代码
复制代码

也可以直接使用foreach,而且主要是因为是枚举元素,类似与数组,list等等之类的,都可以使用Lambda表达式来进行数据的处理

复制代码
复制代码
 Person p = new Person();
            foreach (string item in p)
            {
                Console.WriteLine(item);
            }
            Console.WriteLine("ok");
复制代码
复制代码

4.输出的结果如下:

 

转 https://www.cnblogs.com/yinxuejunfeng/p/9747972.html

 

posted @   dreamw  阅读(469)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示