How can For each...
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();
}
}
}
} }
随机推荐
- 学习《深入理解C#》—— 数据类型、排序和过滤 (第一章1.1---1.2)
引言 在开始看这本书之前看过一些技术博客,填补自己对于一些知识点的不足.无意中发现了<深入理解C#>这本书,本书主要探讨C# 2.C# 3和C# 4的细节与特性,所以做了一下阅读笔记,欢迎 ...
- Struts2_day04--自定义拦截器_Struts2的标签库_表单标签
自定义拦截器 1 在struts2里面有很多的拦截器,这些拦截器是struts2封装的功能,但是在实际开发中,struts2里面的拦截器中可能没有要使用的功能,这个时候需要自己写拦截器实现功能 2 拦 ...
- 打打基础,回头看看avr单片机的定时器、中断和PWM(转)
以前小看了定时器,发现这东西还真的很讲究,那先复习复习吧. 先提提中断:我的理解就是cpu执行时,遇到中断——根据对应的中断源(硬件或软件)——pc定位中断入口地址,然后根据这里的函数指针——跳转到相 ...
- Android下在onCreate中获取控件的宽度和高度(通过回调)
有时候需要在onCreate方法中知道某个View组件的宽度和高度等信息, 而直接调用View组件的getWidth().getHeight().getMeasuredWidth().getMeasu ...
- dbForge mysql数据库比对
Comparison选项卡,新建一个表结构比较, (将source库的表结构变化应用到target库) 下面示例中,source用positec_uat, target用positec_pro ...
- Java中分页功能源码实例
一.源码(后附使用说明) package com.zhiyou100.crm.util; /** * 分页功能 * @author YangXianSheng * */ public class Pa ...
- centos7常用命令集合
版权声明:本文为博主原创文章,未经博主允许不得转载. 目录(?)[+] CentOS7 常用命令集合 这两天一直在对CentOS 7.2进行初体验,各种学习命令肿么用,不过其实大多和DOS是一 ...
- 修改NavigationBar的分根线颜色
[self.navigationController.navigationBar setShadowImage:[Static ColorToImage:[Static colorWithHexStr ...
- If the parts of an organization (e.g., teams, departments, or subdivisions) do not closely reflect the essential parts of the product, or if the relationship between organizations do not reflect the r
https://en.wikipedia.org/wiki/Conway%27s_law
- cross-compler toolchains--clfs
http://www.cnblogs.com/leaven/archive/2010/11/17/1879679.html