IEnumerable

截图来源于https://msdn.microsoft.com/zh-cn/library/system.collections.ienumerable.getenumerator.aspx

IEnumerable只包含一个抽象方法GetEnumerable(),它返回一个可用于循环访问集合的IEnumberator对象。我们可以通过定义foreach语句功能实现并支持非泛型方法的迭代。

在MSDN上给出了一个关于GetEnumerable()方法的例子:

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections; namespace TestInterface
{ public class Person
{
public Person(string fName,string lName)
{
this.firstName = fName;
this.lastName = lName;
} public string firstName;
public string lastName;
} public class People:IEnumerable//继承IEnumerable类,重写GetNumberable()方法
{
private Person[] _peopele;
public People(Person[] pArray)
{
_peopele = new Person[pArray.Length];
for (int i = ; i < pArray.Length; i++)
_peopele[i] = pArray[i];
} IEnumerator IEnumerable.GetEnumerator()//实现GetEnumerable接口
{
return (IEnumerator) GetEnumerator();//调用重写的GetEnumerator方法
} public PeopleEnum GetEnumerator()
{
return new PeopleEnum(_peopele);//返回一个PeopleEnum类型的对象,PeopleEnum继承了IEnumerator类
}
} public class PeopleEnum:IEnumerator
{
public Person[] _people;
int position = -;
/// <summary>
/// 构造函数
/// </summary>
/// <param name="list">
/// _people指针指向list数组
/// </param>
public PeopleEnum(Person[] list)
{
_people = list;
} /// <summary>
///将枚举数推进到集合的下一个元素。 /// </summary>
/// <returns>
/// 成功返回true,失败返回false
/// </returns>
public bool MoveNext()
{
position++;
return (position < _people.Length);
} /// <summary>
/// 将枚举数设置为其初始位置,该位置位于集合中第一个元素之前。
/// </summary>
public void Reset()
{
position = -;
} /// <summary>
/// 获取当前位置的对象
/// </summary>
object IEnumerator.Current
{
get { return Current; }
} /// <summary>
/// 实现接口方法
/// </summary>
public Person Current
{
get
{
try
{
return _people[position];
}
catch(IndexOutOfRangeException)
{
throw new InvalidOperationException();
}
}
}
} class Program
{ static void Main(string[] args)
{
Person[] peopleArray = new Person[]
{
new Person("John","Smith"),
new Person("Jim","Johnson"),
new Person("Sue","Rabon"),
};
People peopleList = new People(peopleArray);//初始化对象集合
foreach (Person p in peopleList)
Console.WriteLine(p.firstName + " " + p.lastName); }
}
}

如果我们将第23-42代码改写如下:

  public class People//继承IEnumerable类,重写GetNumberable()方法
{
private Person[] _peopele;
public People(Person[] pArray)
{
_peopele = new Person[pArray.Length];
for (int i = ; i < pArray.Length; i++)
_peopele[i] = pArray[i];
}
}

即不让People继承IEnumerable类,重写GetNumerator接口的部分也删除掉。那么编译器就会提示:

这是因为People类中没有实现GetNumerator()方法,所以People对象就不能返回一个IEnumerator对象,以至于foreach语句不能遍历Person集合。

IEnumerator

下面来介绍一下IEnumerator

截图来源于:https://msdn.microsoft.com/zh-cn/library/system.collections.ienumerator(v=vs.110).aspx

属性                        描述


Current                获取集合中的当前元素


方法                       描述


MoveNext             将枚举数推进到集合的下一个元素。


Reset                   将枚举数设置为其初始位置,该位置位于集合中第一个元素之前。


正是因为People类中没有实现GetNumerator()方法,所以People对象就不能返回一个IEnumerator对象,那么也就不能使用MoveNext方法,foreach也就不能实现遍历Person集合。

C#接口之IEnumerable,IEnumerator的更多相关文章

  1. IEnumerable, IEnumerator接口

    IEnumerable接口 // Exposes the enumerator, which supports a simple iteration over a non-generic collec ...

  2. C# ~ 从 IEnumerable / IEnumerator 到 IEnumerable<T> / IEnumerator<T> 到 yield

    IEnumerable / IEnumerator 首先,IEnumerable / IEnumerator 接口定义如下: public interface IEnumerable /// 可枚举接 ...

  3. C# 常用接口学习 IEnumerable<T>

    作者:乌龙哈里 时间:2015-10-24 平台:Window7 64bit,Visual Studio Community 2015 本文参考: MSDN IEnumerable<T> ...

  4. ICollection IEnumerable/IEnumerator IDictionaryEnumerator yield

    Enumerable和IEnumerator接口是.NET中非常重要的接口,二者区别: 1. IEnumerable是个声明式的接口,声明实现该接口的类就是“可迭代的enumerable”,但并没用说 ...

  5. c#yield,IEnumerable,IEnumerator

    foreach 在编译成IL后,实际代码如下: 即:foreach实际上是先调用可枚举对象的GetEnumerator方法,得到一个Enumerator对象,然后对Enumerator进行while循 ...

  6. IEnumerable & IEnumerator

    IEnumerable 只有一个方法:IEnumerator GetEnumerator(). INumerable 是集合应该实现的一个接口,这样,就能用 foreach 来遍历这个集合. IEnu ...

  7. C#内建接口:IEnumerable

    这节讲一下接口IEnumerable. 01 什么是Enumerable 在一些返回集合数据的接口中,我们经常能看到IEnumerable接口的身影.那什么是Enumerable呢?首先它跟C#中的e ...

  8. 【Unity|C#】基础篇(20)——枚举器与迭代器(IEnumerable/IEnumerator)

    [学习资料] <C#图解教程>(第18章):https://www.cnblogs.com/moonache/p/7687551.html 电子书下载:https://pan.baidu. ...

  9. [设计模式] Iterator - 迭代器模式:由一份奥利奥早餐联想到的设计模式

    Iterator - 迭代器模式 目录 前言 回顾 UML 类图 代码分析 抽象的 UML 类图 思考 前言 这是一包奥利奥(数组),里面藏了很多块奥利奥饼干(数组中的元素),我将它们放在一个碟子上慢 ...

随机推荐

  1. xapp1052之dma_test.v

    dma_test是针对dma硬件设计的仿真测试文件,文件包括DMA写数据测试,DMA读数据测试以及DMA读写数据测试.这个测试文件其实就是模拟pc的应用程序对fpga设备进行DMA读写. DMA写测试 ...

  2. iptables允许一个ip访问本机的某个端口

    需求是redis允许特定客服端连接: -A INPUT -s .xx.xx.xxx/ -p tcp --dport -j ACCEPT

  3. mongoose中给字段添加索引的方法

    mongoose中给字段添加索引的方法有两种,一种通过在定义schema的时候配置,如: var animalSchema = new Schema({ name: String, type: Str ...

  4. oracle日期合并 分别用逗号或者分号隔开

    逗号隔开',' select LISTAGG(SUBSTR(TO_CHAR(FREESTARTTIME,,) ,)),',')WITHIN GROUP (ORDER BY TPF.FREEID) AS ...

  5. linux系统资源网站

    http://upstream.rosalinux.ru/    API/ABI changes analysis for C/C++ libraries

  6. CentOS 7.0 以后的几件事情

    1.当最大化时隐藏标题栏 或者使用tweak tool 在字体中将标题栏字体设置为0...建议这个方法. 2.添加epel源 yum -y --nogpgcheck install http://do ...

  7. [转]编写 android.mk 中 LOCAL_C_INCLUDES 的技巧

    看原文请移步:编写 android.mk 中 LOCAL_C_INCLUDES 的技巧 在编写android.mk的过程中,免不了要修改LOCAL_C_INCLUDES来设置头文件的include目录 ...

  8. appium安卓自动化的 常用driver方法封装

    appium安卓自动化的 常用driver方法封装 做安卓自动化的时候,很多方法写起来会造成代码冗余,把这部分封装起来 ,添加到androidUI工具类里,随时可调用 都放在这个类下面: @Compo ...

  9. python+xpath+requests爬取维基百科历史上的今天

    import requests import urllib.parse import datetime from lxml import etree fhout = open("result ...

  10. 让一个div始终固定在页面的某一固定位置的方法

    方法一:直接用position:fixed 方法二:写一个滚动条滚动事件,让这个div设置 position:absolute 该top的距离等于滚动的距离scrollTop() 写法如下:$(win ...