关于IEnumerator<T>泛型枚举器 和 IEnumerable<T>

在开发中我们经常会用到 IEnumerable<T> xxx 或者 List<T> xxx 这种集合或者集合接口,实际上就是一个线性表嘛
然后结合C#提供的语法糖 foreach 遍历 用起来真的是清甜,哈哈,闲话不多说 下面直奔主题
1.枚举器和可枚举类型 foreach语句可以循环一次取数组中元素的原理:数组可以提供一个枚举器Enumerator的对象,枚举器可以知道元素的次序。 获取一个对象枚举器的方法是调用对象的GetEnumerator方法。实现了GetEnumerator方法的类型叫做可枚举类型Enumerable。 2 IEnumerator接口 实现了IEnumerator接口的枚举器包含3个函数成员:Current、MoveNext以及ReSet
IEnumerator接口 可以看到 GetEnumerator() 抽象方法 并且返回的是IEnumerable 对象

IEnumerator 接口 三个 抽象成员 Current 当前对象 foreach 中 遍历的的 item项 应该就是返回的这个属性 MoveNext()方法 移动到下一个元素
这里有没有想起 Node * next 啊 哈哈哈~(忽略) 当然 IEnumerator<T> 必然也是 继承IEnumerator的


下面 我就写一个 QueueList<T> 来实现下IEnumerable<T> 当然接口IEnumerable<T> 也是是继承IEnumerable的 这里就不贴码了
 public class QueueList<T> : IEnumerable<T>
    {
        public T[] list =new T[50]; // 并不严谨望广大网友更正
        public int length;
        public int index =0;
        public IEnumerator<T> GetEnumerator()
        {
            return new QueuelistEnumerator<T>(this);
        }

        public void Add(T element)
        {
            list[index] = element;
            length++;
            index++;
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            throw new NotImplementedException();
        }
    }
这里用数组模拟下 因为我们常用的list是不限长度的可以自动扩容 而我这个可以明显的看到当 QueueList中的元素超过50时候就会报错了 暂时就用这个代替下
接下来 枚举器类 QueuelistEnumerator<T>继承 IEnumerator<T>
  public class QueuelistEnumerator<T> : IEnumerator<T>
    {
        private T current;
       // public T Current =>current;

        public T Current { get { return current; } }

        object IEnumerator.Current => throw new NotImplementedException();

        public int index;

        public QueueList<T> queuelist;

        public QueuelistEnumerator(QueueList<T> _list)
        {
            queuelist = _list;
            index = -1;
        }

        public void Dispose()
        {
         
        }

        public bool MoveNext()
        {
            if (index < queuelist.length - 1)
            {
                current = queuelist.list[++index];
                return true;
            }
            else
            {
                current = default(T);
                return false;
            }
        }

        public void Reset()
        {
            index = -1;
        }
    }
接下来我们就测试下 QueueList<T>

效果还行哦 哈哈~ 不是很完备还请大佬们多多指正.......

 

 
posted @ 2018-09-02 16:09  万年锋刀志  阅读(334)  评论(0编辑  收藏  举报