关于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>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
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>


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

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