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. TRIZ系列-创新原理-9~11-预先反作用原理、预处理原理、预先防范原理

    一.预先反作用原理表述例如以下: 1)预先给物体施加反作用,以补偿过量的或者不想要的压力. 假设知道系统在执行过程中,会有不利的或者有害的作用(负面作用)产生,则能够预先採取一定的措施来抵消.控制这样 ...

  2. FPGA三分频,五分频,奇数分频

    我们在做FPGA设计时,有时会用到时钟频率奇数分频的频率,例如笔者FPGA的晶振为50M,当我们需要10M的时钟时,一种方式可以使用DCM或PLL获取,系统会内部分频到10M,但其实VERILOG内部 ...

  3. FZU Problem 2030 括号问题

    Problem Description 给出一个字符串,其中包括3种字符: ‘(‘, ‘)’, ‘?’.其中?表示这个字符可以是’(‘也可以是’)’. 现在给出字符串S,你可以在’?’处填写’(‘ 或 ...

  4. spark内存概述

    转自:https://github.com/jacksu/utils4s/blob/master/spark-knowledge/md/spark%E5%86%85%E5%AD%98%E6%A6%82 ...

  5. Mac下Python安装目录

    /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages

  6. js用new Object创建json数据

    var str = '';var json = new Object;var arr =new Array(); for(var i =0; i<4;i++){        var jsons ...

  7. JVM 内存分配机制总结

    大多数 JVM 将内存区域划分为 Method Area(Non-Heap)(方法区),Heap(堆),Program Counter Register(程序计数器), VM Stack(虚拟机栈,也 ...

  8. war 宽度变窄

    1.打开开始菜单-运行-输入Regedit 打开注册表编辑器 展开 HKEY_CURRENT_USER 继续展开 Software继续展开 Blizzard Entertainment 在Warcra ...

  9. 【Unity笔记】使用协程(Coroutine)异步加载场景

    using UnityEngine; using System.Collections; using UnityEngine.SceneManagement; using System; public ...

  10. 【SpringMVC笔记】第三课 处理器映射器+处理器适配器

    第二课的例子中,在springmvc.xml中配置使用了第一种处理器映射器和处理器适配器,如下所示. <!-- 配置第一种处理器映射器 BeanNameUrlHandlerMapping --& ...