首页 技术 正文
技术 2022年11月16日
0 收藏 497 点赞 2,749 浏览 1562 个字
在开发中我们经常会用到 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<T>泛型枚举器 和 IEnumerable<T>
IEnumerator 接口 三个 抽象成员 Current 当前对象 foreach 中 遍历的的 item项 应该就是返回的这个属性 MoveNext()方法 移动到下一个元素
这里有没有想起 Node * next 啊 哈哈哈~(忽略) 当然 IEnumerator<T> 必然也是 继承IEnumerator的关于IEnumerator<T>泛型枚举器 和 IEnumerable<T>
下面 我就写一个 QueueList<T> 来实现下IEnumerable<T> 当然接口IEnumerable<T> 也是是继承IEnumerable的 这里就不贴码了
 public class QueueList<T> : IEnumerable<T>
{
public T[] list =new T[]; // 并不严谨望广大网友更正
public int length;
public int index =;
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>
关于IEnumerator<T>泛型枚举器 和 IEnumerable<T>
效果还行哦 哈哈~ 不是很完备还请大佬们多多指正.......
 
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,497
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,910
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,744
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,497
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,135
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,298