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. ios开发之--UIWebView全属性

    最近的项目当中需要用到html和ios的交互,所以就凑空整理一下,所有webView相关的方法和属性,如有不对的地方,请大家不吝指教! 代码如下: 1,创建webview并设置代理 UIWebView ...

  2. import cx_Oracle报错,提示importError: DLL load failed: 不是有效的Win32程序。

    问题说明1:WIN32,python是2.7版本,本地oracle client是32位的.import cx_Oracle报错,提示importError: DLL load failed: 该模块 ...

  3. skeleton

    响应式模版 伯乐在线:http://hao.jobbole.com/skeleton/ cdn  : https://cdn.bootcss.com/skeleton/2.0.4/skeleton.c ...

  4. 【BZOJ3648】寝室管理 树分治

    [BZOJ3648]寝室管理 Description T64有一个好朋友,叫T128.T128是寄宿生,并且最近被老师叫过去当宿管了.宿管可不是一件很好做的工作,碰巧T128有一个工作上的问题想请T6 ...

  5. 【BZOJ1857】[Scoi2010]传送带 三分套三分

    [BZOJ1857][Scoi2010]传送带 Description 在一个2维平面上有两条传送带,每一条传送带可以看成是一条线段.两条传送带分别为线段AB和线段CD.lxhgww在AB上的移动速度 ...

  6. R语言中的一些函数

    1.控制输出数字的精度 format(123.123,digits=4) 输出4位数字123.1,如果整数超过4位,小数部分就全被略去. options(digits=4) 功能同上,不过在Rsess ...

  7. 获取 js DOM元素中绑定的所有事件,模仿 chrome getEventListeners

    偶尔看到了这个问题,如何用JS获取元素某一事件上绑定的所有Listener? 突然觉得好像是有解决办法的,查了下,在 chrome 下,支持 window.getEventListeners(obj) ...

  8. 云计算之路-阿里云上:对“黑色n秒”问题的最终猜想——CPU C-states引起的

    如果说2013年云计算之路的主题是“踩坑”,那么2014年我们希望云计算之路的主题变成“填坑”——当然填坑是阿里云来完成的,我们只是见证曾经的坑坑洼洼变成平坦大道. 15号(周四)晚上我们发现了SLB ...

  9. gdb常见命令(未完,待续)

    // 编译文件时,带参-g > gcc -g test.c // 进入gdb调试界面 > gdb a.out 或者 > gdb > file a.out // 查看文件内容 & ...

  10. 巨蟒python全栈开发flask15项目开始7

    1.连续收取未读消息&&未读消息所属人 2.Pypinyin NLP中文同音字识别 3.jieba分词 4.Gemsim框架之LsiModel稀疏矩阵相似度 5.Gensim的应用 6 ...