Answer:
 

I understand the IEnumerator/IEnumerable methods and properties and also how they are interrelated. But I fail to understand from the foreach loop perspective. Say for example, if I say the following line of code, how does the compiler look at foreach loop and break it down to IEnumerable/IEnumerator for every occurance of foreach loop in your code. In other words, what happens under the hood? I tried to go through couple of articles on the web. But they were NOT looked from the foreach loop perspective or I might have failed to understand. Could somebody explain with the example or direct me to any articles that explains clearly. All help is greatly appreciated.

Answer: To keep it short the compiler doesn't do much. It just translates the foreach code into a while under the hood. Here's an example:

List<int> list = new List<int>;

........

foreach(int item in list)

{

//Do stuff

}

Becomes:

Enumerator<int> enum = ((IEnumerable<int>)list).GetEnumerator();

enum.Reset();

while(enum.MoveNext())

{

int item = enum.Current;

//Do stuff

}

or something very close to that. The acual code compiled most likely has a try / finally block around the while to dispose the enumerator

IEnumerable is the base interface for all non-generic collections that can be enumerated. For the generic version of this interface see System.Collections.Generic.IEnumerable<T>. IEnumerable contains a single method, GetEnumerator, which returns an IEnumerator. IEnumerator provides the ability to iterate through the collection by exposing a Current property and MoveNext and Reset methods.

It is a best practice to implement IEnumerable and IEnumerator on your collection classes to enable the foreach (For Each in Visual Basic) syntax, however implementing IEnumerable is not required. If your collection does not implement IEnumerable, you must still follow the iterator pattern to support this syntax by providing a GetEnumerator method that returns an interface, class or struct. When using Visual Basic, you must provide an IEnumerator implementation, which is returned by GetEnumerator. When developing with C# you must provide a class that contains a Current property, and MoveNext and Reset methods as described by IEnumerator, but the class does not have to implement IEnumerator.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections; namespace CSharpExam
{
public class TestInumerable
{
public static void Run()
{
Person[] peopleArray = new Person[]
{
new Person("Steven", "Xia"),
new Person("Jim", "Johnson"),
new Person("Sue", "Rabon"),
}; People peopleList = new People(peopleArray);
foreach (Person p in peopleList)
Console.WriteLine(p.firstName + " " + p.lastName); }
} 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
{
private Person[] _people;
public People(Person[] pArray)
{
_people = new Person[pArray.Length]; for (int i = ; i < pArray.Length; i++)
{
_people[i] = pArray[i];
}
} #region IEnumerable 成员 public PeopleEnum GetEnumerator()
{
return new PeopleEnum(_people);
} #endregion
} public class PeopleEnum //: IEnumerator
{
public Person[] _people; // Enumerators are positioned before the first element
// until the first MoveNext() call.
int position = -; public PeopleEnum(Person[] list)
{
_people = list;
} public bool MoveNext()
{
position++;
return (position < _people.Length);
} public void Reset()
{
position = -;
} public object Current
{
get
{
try
{
return _people[position];
}
catch (IndexOutOfRangeException)
{
throw new InvalidOperationException();
}
}
}
} }

随机推荐

  1. VS2008设置快捷键Ctrl+W关闭当前打开的文本编辑器窗口

    好多友好的软件关闭多标签页的当前页时都有Ctrl+W的快捷键,如Chrome浏览器,使用起来还是很方便的. 但是作为程序员,使用VS2008时有时会打开好多C++或C#源文件,需要关闭某个源文件时你需 ...

  2. XML Publiser For Excel Template

    1.XML Publisher定义数据 2.XML Publisher定义模板 模板类型选择Microsoft Excel,默认输出类型选择Excel,上传.xls模板 3.定义并发程序 4.定义请求 ...

  3. [Web] 如何实现Web服务器和应用服务器的负载均衡?

    本文对Web服务器和应用服务器的负载均衡进行说明. 在负载均衡的思路下,多台服务器为对称方式,每台服务器都具有同等的地位,可以单独对外提供服务而无须其他服务器的辅助.通过负载分担技术,将外部发送来的请 ...

  4. 【BZOJ1935/4822】[Shoi2007]Tree 园丁的烦恼/[Cqoi2017]老C的任务 树状数组

    题意:两道题差不多,都是给你一堆平面上的点,每个点有权值,然后m次询问求某一矩形区域内的点权和 题解:先离散化,然后将询问拆成左右两条线段,然后将点和这些线段一起按x坐标排序,在y轴上维护树状数组.然 ...

  5. 单台centos7.3 虚拟机实现主从复制和哨兵集群

    环境: centos7.3一台 部署图: 从服务器配置: slaveof 哨兵配置: port sentinel monitor m1 127.0.0.1 6379 2 sentinel monito ...

  6. Oracle中与日期时间有关的运算函数

    1            ADD_MONTHS 格式:ADD_MONTHS(D,N) 说明:返回日期时间D加N月后对应的日期时间.N为正时则表示D之后:N为负时则表示为D之前:N为小数则会自动先删除小 ...

  7. LeetCode 笔记系列 14 N-Queen II [思考的深度问题]

    题目: Follow up for N-Queens problem. Now, instead outputting board configurations, return the total n ...

  8. 对 js 高程 Preflighted Reqeusts 的理解

    看JS高程遇到 Preflighted Reqeusts不大理解,遂百度下: 转自:http://todoit.me/ajax-preflight/ 最近在做一个 VUE 的项目的时候, 和后端的小伙 ...

  9. hibernate配置文件分析

    <!--标准的XML文件的起始行,version='1.0'表明XML的版本,encoding='gb2312'表明XML文件的编码方式--> <?xml version='1.0' ...

  10. Game 游戏开发

    Scut:https://git.oschina.net/scutgame/Scut unity3d:http://unity3d.com/get-unity cocos2d-x:http://www ...