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();
}
}
}
} }
随机推荐
- 将Oracle数据库转换为SQL Server
(转发)近期为公司的一个项目数据库进行了转换,将Oracle的Db转换为SqlServer(2000或2005均可),一开始在网上找了一些资料,发现有个工具叫SwisSql的,尝试了一下,没成功,继续 ...
- UE4中VR模式下窗口单目双目的问题
如果要是单目的话使用HMD MIRROR MODE 3或者4
- Android解析JSON速度对比
转载参考:http://blog.csdn.net/h3c4lenovo/article/details/26568531 { "testStr":"这是String的测 ...
- c++11 lambda(了解)
this->send_change_equip = ([this](ChangeEquipPT channge) { send_cmd(s2c_change_equip, &channg ...
- 那个你经常用的abs函数(取绝对值)真的总是返回非负数吗?
前几天在牛客网看到一道关于abs()函数返回值的题目,见下图,当时还没反应过来,第一反应是:自从我开始学C语言,就知道它是用来求int数的绝对值的,返回值当然是0或者正数啊,一看答案就是A. 后来思来 ...
- c#基础 第四讲
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threa ...
- 【BZOJ4726】[POI2017]Sabota? 树形DP
[BZOJ4726][POI2017]Sabota? Description 某个公司有n个人, 上下级关系构成了一个有根树.其中有个人是叛徒(这个人不知道是谁).对于一个人, 如果他 下属(直接或者 ...
- 关东升的iOS实战系列图书 《iOS实战:入门与提高卷(Swift版)》已经上市
承蒙广大读者的厚爱我的 <iOS实战:入门与提高卷(Swift版)>京东上市了,欢迎广大读者提出宝贵意见.http://item.jd.com/11766718.html ...
- 160307、Java调用Oracle存储过程返回结果集
一:无返回值的存储过程调用 存储过程: CREATE OR REPLACE PROCEDURE PRO_1(PARA1 IN VARCHAR2,PARA2 IN VARCHAR2) AS BEGI ...
- [LeetCode] 1.Two Sum - Swift
1. Two Sum Given an array of integers, return indices of the two numbers such that they add up to a ...