IEnumerable和IEnumerator 详解 (转)
原文链接:http://blog.csdn.net/byondocean/article/details/6871881
参考链接:http://www.cnblogs.com/hsapphire/archive/2010/04/16/1713211.html
初学C#的时候,老是被IEnumerable、IEnumerator、ICollection等这样的接口弄的糊里糊涂,我觉得有必要切底的弄清楚IEnumerable和IEnumerator的本质。
下面我们先看IEnumerable和IEnumerator两个接口的语法定义。其实IEnumerable接口是非常的简单,只包含一个抽象的 方法GetEnumerator(),它返回一个可用于循环访问集合的IEnumerator对象。IEnumerator对象有什么呢?它是一个真正的 集合访问器,没有它,就不能使用foreach语句遍历集合或数组,因为只有IEnumerator对象才能访问集合中的项,假如连集合中的项都访问不 了,那么进行集合的循环遍历是不可能的事情了。那么让我们看看IEnumerator接口有定义了什么东西。看下图我们知道IEnumerator接口定 义了一个Current属性,MoveNext和Reset两个方法,这是多么的简约。既然IEnumerator对象时一个访问器,那至少应该有一个 Current属性,来获取当前集合中的项吧。
MoveNext方法只是将游标的内部位置向前移动(就是移到一下个元素而已),要想进行循环遍历,不向前移动一下怎么行呢?


详细讲解:
说到IEnumerable总是会和IEnumerator、foreach联系在一起。
C# 支持关键字foreach,允许我们遍历任何数组类型的内容:
//遍历数组的项
int[] myArrayOfInts = {10,20,30,40};
foreach(int i in my myArrayOfInts)
{
Console.WirteLine(i);
}
虽然看上去只有数组才可以使用这个结构,其实任何支持GetEnumerator()方法的类型都可以通过foreach结构进行运算。
- public class Garage
- {
- Car[] carArray = new Car[4]; //在Garage中定义一个Car类型的数组carArray,其实carArray在这里的本质是一个数组字段
- //启动时填充一些Car对象
- public Garage()
- {
- //为数组字段赋值
- carArray[0] = new Car("Rusty", 30);
- carArray[1] = new Car("Clunker", 50);
- carArray[2] = new Car("Zippy", 30);
- carArray[3] = new Car("Fred", 45);
- }
- }
理想情况下,与数据值数组一样,使用foreach构造迭代Garage对象中的每一个子项比较方便:
- //这看起来好像是可行的
- lass Program
- {
- static void Main(string[] args)
- {
- Console.WriteLine("*********Fun with IEnumberable/IEnumerator************\n");
- Garage carLot = new Garage();
- //交出集合中的每一Car对象吗
- foreach (Car c in carLot)
- {
- Console.WriteLine("{0} is going {1} MPH", c.CarName, c.CurrentSpeed);
- }
- Console.ReadLine();
- }
- }
让人沮丧的是,编译器通知我们Garage类没有实现名为GetEnumerator()的方法(显然用foreach遍历Garage对象是 不可能的事情,因为Garage类没有实现GetEnumerator()方法,Garage对象就不可能返回一个IEnumerator对象,没有 IEnumerator对象,就不可能调用方法MoveNext(),调用不了MoveNext,就不可能循环的了)。这个方法是有隐藏在 System.collections命名空间中的IEnumerable接口定义的。(特别注意,其实我们循环遍历的都是对象而不是类,只是这个对象是一个集合对象)
支持这种行为的类或结构实际上是宣告它们向调用者公开所包含的子项:
//这个接口告知调方对象的子项可以枚举
public interface IEnumerable
{
IEnumerator GetEnumerator();
}
可以看到,GetEnumerator方法返回对另一个接口System.Collections.IEnumerator的引用。这个接口提供了基础设施,调用方可以用来移动IEnumerable兼容容器包含的内部对象。
//这个接口允许调用方获取一个容器的子项
public interface IEnumerator
{
bool MoveNext(); //将游标的内部位置向前移动
object Current{get;} //获取当前的项(只读属性)
void Reset(); //将游标重置到第一个成员前面
}
所以,要想Garage类也可以使用foreach遍历其中的项,那我们就要修改 Garage类型使之支持这些接口,可以手工实现每一个方法,不过这得花费不少功夫。虽然自己开发GetEnumerator()、 MoveNext()、Current和Reset()也没有问题,但有一个更简单的办法。因为System.Array类型和其他许多类型(如 List)已经实现了IEnumerable和IEnumerator接口,你可以简单委托请求到System.Array,如下所示:
- namespace MyCarIEnumerator
- {
- public class Garage:IEnumerable
- {
- Car[] carArray = new Car[4];
- //启动时填充一些Car对象
- public Garage()
- {
- carArray[0] = new Car("Rusty", 30);
- carArray[1] = new Car("Clunker", 50);
- carArray[2] = new Car("Zippy", 30);
- carArray[3] = new Car("Fred", 45);
- }
- public IEnumerator GetEnumerator()
- {
- return this.carArray.GetEnumerator();
- }
- }
- }
- //修改Garage类型之后,就可以在C#foreach结构中安全使用该类型了。
- //除此之外,GetEnumerator()被定义为公开的,对象用户可以与IEnumerator类型交互:
- namespace MyCarIEnumerator
- {
- class Program
- {
- static void Main(string[] args)
- {
- Console.WriteLine("*********Fun with IEnumberable/IEnumerator************\n");
- Garage carLot = new Garage();
- //交出集合中的每一Car对象吗
- foreach (Car c in carLot) //之所以遍历carLot,是因为carLot.GetEnumerator()返回的项时Car类型,这个十分重要
- {
- Console.WriteLine("{0} is going {1} MPH", c.CarName, c.CurrentSpeed);
- }
- Console.WriteLine("GetEnumerator被定义为公开的,对象用户可以与IEnumerator类型交互,下面的结果与上面是一致的");
- //手动与IEnumerator协作
- IEnumerator i = carLot.GetEnumerator();
- while (i.MoveNext())
- {
- Car myCar = (Car)i.Current;
- Console.WriteLine("{0} is going {1} MPH", myCar.CarName, myCar.CurrentSpeed);
- }
- Console.ReadLine();
- }
- }
- }
下面我们来看看手工实现IEnumberable接口和IEnumerator接口中的方法:
- namespace ForeachTestCase
- {
- //继承IEnumerable接口,其实也可以不继承这个接口,只要类里面含有返回IEnumberator引用的GetEnumerator()方法即可
- class ForeachTest:IEnumerable {
- private string[] elements; //装载字符串的数组
- private int ctr = 0; //数组的下标计数器
- /// <summary>
- /// 初始化的字符串
- /// </summary>
- /// <param name="initialStrings"></param>
- ForeachTest(params string[] initialStrings)
- {
- //为字符串分配内存空间
- elements = new String[8];
- //复制传递给构造方法的字符串
- foreach (string s in initialStrings)
- {
- elements[ctr++] = s;
- }
- }
- /// <summary>
- /// 构造函数
- /// </summary>
- /// <param name="source">初始化的字符串</param>
- /// <param name="delimiters">分隔符,可以是一个或多个字符分隔</param>
- ForeachTest(string initialStrings, char[] delimiters)
- {
- elements = initialStrings.Split(delimiters);
- }
- //实现接口中得方法
- public IEnumerator GetEnumerator()
- {
- return new ForeachTestEnumerator(this);
- }
- private class ForeachTestEnumerator : IEnumerator
- {
- private int position = -1;
- private ForeachTest t;
- public ForeachTestEnumerator(ForeachTest t)
- {
- this.t = t;
- }
- #region 实现接口
- public object Current
- {
- get
- {
- return t.elements[position];
- }
- }
- public bool MoveNext()
- {
- if (position < t.elements.Length - 1)
- {
- position++;
- return true;
- }
- else
- {
- return false;
- }
- }
- public void Reset()
- {
- position = -1;
- }
- #endregion
- }
- static void Main(string[] args)
- {
- // ForeachTest f = new ForeachTest("This is a sample sentence.", new char[] { ' ', '-' });
- ForeachTest f = new ForeachTest("This", "is", "a", "sample", "sentence.");
- foreach (string item in f)
- {
- System.Console.WriteLine(item);
- }
- Console.ReadKey();
- }
- }
- }
IEnumerable<T>接口
实现了IEnmerable<T>接口的集合,是强类型的。它为子对象的迭代提供类型更加安全的方式。
- public class ListBoxTest:IEnumerable<String>
- {
- private string[] strings;
- private int ctr = 0;
- #region IEnumerable<string> 成员
- //可枚举的类可以返回枚举
- public IEnumerator<string> GetEnumerator()
- {
- foreach (string s in strings)
- {
- yield return s;
- }
- }
- #endregion
- #region IEnumerable 成员
- //显式实现接口
- System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
- {
- return GetEnumerator();
- }
- #endregion
- //用字符串初始化列表框
- public ListBoxTest(params string[] initialStrings)
- {
- //为字符串分配内存空间
- strings = new String[8];
- //复制传递给构造方法的字符串
- foreach (string s in initialStrings)
- {
- strings[ctr++] = s;
- }
- }
- //在列表框最后添加一个字符串
- public void Add(string theString)
- {
- strings[ctr] = theString;
- ctr++;
- }
- //允许数组式的访问
- public string this[int index]
- {
- get {
- if (index < 0 || index >= strings.Length)
- {
- //处理不良索引
- }
- return strings[index];
- }
- set {
- strings[index] = value;
- }
- }
- //发布拥有的字符串数
- public int GetNumEntries()
- {
- return ctr;
- }
- }
- class Program
- {
- static void Main(string[] args)
- {
- //创建一个新的列表框并初始化
- ListBoxTest lbt = new ListBoxTest("Hello", "World");
- //添加新的字符串
- lbt.Add("Who");
- lbt.Add("Is");
- lbt.Add("Douglas");
- lbt.Add("Adams");
- //测试访问
- string subst = "Universe";
- lbt[1] = subst;
- //访问所有的字符串
- foreach (string s in lbt)
- {
- Console.WriteLine("Value:{0}", s);
- }
- Console.ReadKey();
- }
- }
综上所述,一个类型是否支持foreach遍历,必须满足下面条件:
方案1:让这个类实现IEnumerable接口
方案2:这个类有一个public的GetEnumerator的实例方法,并且返回类型中有public 的bool MoveNext()实例方法和public的Current实例属性。
IEnumerable和IEnumerator 详解 (转)的更多相关文章
- IEnumerable和IEnumerator 详解 分类: C# 2014-12-05 11:47 18人阅读 评论(0) 收藏
原:<div class="article_title"> <span class="ico ico_type_Original">&l ...
- IEnumerable和IEnumerator 详解
初学C#的时候,老是被IEnumerable.IEnumerator.ICollection等这样的接口弄的糊里糊涂,我觉得有必要切底的弄清楚IEnumerable和IEnumerator的本质. 下 ...
- IEnumerable和IEnumerator 详解 【转】
初学C#的时候,老是被IEnumerable.IEnumerator.ICollection等这样的接口弄的糊里糊涂,我觉得有必要切底的弄清楚IEnumerable和IEnumerator的本质. 下 ...
- 转载 IEnumerable和IEnumerator 详解
初学C#的时候,老是被IEnumerable.IEnumerator.ICollection等这样的接口弄的糊里糊涂,我觉得有必要切底的弄清楚IEnumerable和IEnumerator的本质. 下 ...
- IEnumerable和IEnumerator详解
引言 IEnumerable是可枚举的所有非泛型集合的基接口, IEnumerable包含一个方法GetEnumerator(),该方法返回一个IEnumerator:IEnumerator提供通过C ...
- IEnumerable 使用foreach 详解
自己实现迭代器 yield的使用 怎样高性能的随机取IEnumerable中的值 我们先思考几个问题: 为什么在foreach中不能修改item的值? 要实现foreach需要满足什么条件? 为什么L ...
- C# ~ 从 IEnumerable / IEnumerator 到 IEnumerable<T> / IEnumerator<T> 到 yield
IEnumerable / IEnumerator 首先,IEnumerable / IEnumerator 接口定义如下: public interface IEnumerable /// 可枚举接 ...
- IEnumerator和IEnumerable详解
IEnumerator和IEnumerable 从名字常来看,IEnumerator是枚举器的意思,IEnumerable是可枚举的意思. 了解了两个接口代表的含义后,接着看源码: IEnumerat ...
- IEnumerable<T> 接口和GetEnumerator 详解
IEnumerable<T> 接口 .NET Framework 4.6 and 4.5 公开枚举数,该枚举数支持在指定类型的集合上进行简单迭代. 若要浏览此类型的.NET Frame ...
随机推荐
- 某网SQL注入漏洞实战
root@kali:~# sqlmap -u http://dn.you.com/shop.php?id=10 -v 1 --dbs available databases [8]: [*] ...
- Java中==、equals、hashcode的区别与重写equals以及hashcode方法实例(转)
Java中==.equals.hashcode的区别与重写equals以及hashcode方法实例 原文地址:http://www.cnblogs.com/luankun0214/p/4421770 ...
- ShareSDK短信验证码集成详细步骤
1.这里使用的是ShareSDK网的短信验证码SDK 官网 http://www.mob.com 先去http://www.mob.com/#/reg 注册成为开发者 填写相应的信息,邮箱账号,然后 ...
- WPF Caliburn.Micro ListView 批量删除,有其他方法的大家一起交流一下
做这种批量删除的时候我的想法是获取每行的ID,然后更具ID删除,看过一些博客,大部分都是直接写在.CS文件里面,将ListView和CheckBox关联起来,最后用checkbox ck=sender ...
- swift网络编程入门应用:天气预报
学习来自<小波说雨燕 第二季 网络编程(入门篇)> 工具:xcode6.4 首先在Main.storyborad中添加并设置好三个label做简单的界面显示: import UIKit / ...
- 原生JS获取各种高度宽度、浏览器窗口滚动条的位置、元素的几何尺寸名
1)关于 pageX, clienX,offsetX,layerX pageX:鼠标在页面上的位置,从页面左上角开始,即是以页面为参考点,不随滑动条移动而变化 clientX:鼠标在页面上可视区域的位 ...
- nginx安装过程,报错处理:make[1]: *** [objs/addon/src/bson.o] Error 1
nginx安装过程中,经常会有各种错误: 具体安装步骤这里不做说明,网上一搜大把: 主要分析安装过程中遇到的问题 在make编译的时候,若报如下错误: cc1: warnings being trea ...
- SoapUI接口测试实例(webservice接口)
接口测试步骤 注:以测试queryHistoryAccepts接口作举例. 1. 用户登录获取SessionKey实体信息 注:由于大部分的接口都需要SessionKey实体的信息,因此测试那些接口都 ...
- ip_forward
查看 cat /proc/sys/net/ipv4/ip_forward 如果是0表示没开启,1表示开启了 临时修改 echo "1" > /proc/sys/net/ ...
- 在Web api2 中传递复杂参数的一点心得
这两天在做的一个项目基于webapi2,期间遇到了复杂参数传递的问题.其中刚好看到园友的这篇文章,但是我测试收结果是失败的,还不知道是什么原因.最终经过思考后,找到了一种方法,和大家分享下. 在前端我 ...