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. Angular2 组件与模板 -- 输入和输出属性

    Input and Output properties 输入属性是一个带有@Input 装饰器的可设置属性,当它通过属性绑定的形式被绑定时,值会"流入"到这个属性. 输出属性是一个 ...

  2. Hadoop1.2.1 伪分布式安装

    Hadoop1.2.1 单机模式安装 Hadoop组件依赖图(从下往上看) 安装步骤: 详细步骤: 设置ssh自动登录(如下图): 1.输入命令 [ssh-keygen -t rsa],然后一直按回车 ...

  3. 1-1、superset开发环境搭建

    在对superset进行二次开发的过程中,往往需要搭建本地开发环境,修改后立即看到效果,下面我们就讲下开发环境的搭建. 1.打开PyCharm,在菜单栏上执行VCS-->Checkout fro ...

  4. python基础之1-安装

    author:headsen chen   date :2018-03-22  17:16:14 notice :This article created by headsen chen and no ...

  5. iOS 7 Master-Detail模板不好用

    将storyboard->use size classes disabled

  6. SQL使用union合并查询结果(转载)

    1.UNION的作用  UNION 指令的目的是将两个 SQL 语句的结果合并起来.从这个角度来看, UNION 跟 JOIN 有些许类似,因为这两个指令都可以由多个表格中撷取资料. UNION 的一 ...

  7. vsftp or pureftpd

    一.安装pureftpd //这个软件比vsftp配置起来更加灵活和安全. /*官网是 http://www.pureftpd.org/project/pure-ftpd*/ [root@localh ...

  8. mysql 创建函数ERROR 1418 (HY000): This function has none of DETERMINISTIC, NO SQL, or READS SQL DATA in its declaration and binary logging is enabled (you *might* want to use the less safe log_bin_trust_f

    mysql 创建函数的时候 报错 ERROR 1418 (HY000): This function has none of DETERMINISTIC, NO SQL, or READS SQL D ...

  9. 如何实现手游app瘦身?

    手游服务商来说,手游包体大一直是个很困扰的问题.一款手游产品而言,包体大小和更新方式对于有效用户的转化率往往起到非常关键的作用,话说手游安装包越小,用户转化率越高,那该如何实现app瘦身呢? 工具/原 ...

  10. windows 下 方便工作的bat文件批处理命令

    1.删除目录下 不包含某串字符的文件: @echo offfor /f "delims=" %%a in ('dir /s /a-d/b *.mp3') do ( echo &qu ...