Mar*_*ell 160
实际上,严格来说,您需要使用的foreach只是一个使用方法和属性GetEnumerator()返回内容的公共方法.但是,最常见的含义是"实现/ ,返回/的东西" .bool MoveNext()? Current {get;}IEnumerableIEnumerable<T>IEnumeratorIEnumerator<T>
通过暗示,这包括任何实现ICollection/ ICollection<T>,如像什么Collection<T>,List<T>,阵列(T[])等.因此,任何标准的"数据集"将通常支持foreach.
为了证明第一点,以下工作正常:
using System;
class Foo {
public int Current { get; private set; }
private int step;
public bool MoveNext() {
if (step >= 5) return false;
Current = step++;
return true;
}
}
class Bar {
public Foo GetEnumerator() { return new Foo(); }
}
static class Program {
static void Main() {
Bar bar = new Bar();
foreach (int item in bar) {
Console.WriteLine(item);
}
}
}
Run Code Online (Sandbox Code Playgroud)
它是如何工作的?
像foreach(int i in obj) {...}有点类似的foreach循环等同于:
var tmp = obj.GetEnumerator();
int i; // up to C# 4.0
while(tmp.MoveNext()) {
int i; // C# 5.0
i = tmp.Current;
{...} // your code
}
Run Code Online (Sandbox Code Playgroud)
但是,有变化.例如,枚举器(tmp)支持IDisposable,它也被使用(类似于using).
注意循环中内部(C#5.0)与外部(上升C#4.0)的声明" int i" 的位置不同.如果您在代码块中使用匿名方法/ lambda,这一点很重要.但那是另一个故事;-pi
来自MSDN:
该
foreach语句为数组或对象集合中的每个元素重复一组嵌入式语句.该foreach语句用于迭代集合以获取所需信息,但不应用于更改集合的内容以避免不可预测的副作用.(强调我的)
所以,如果你有一个数组,你可以使用foreach语句迭代数组,如下所示:
int[] fibarray = new int[] { 0, 1, 2, 3, 5, 8, 13 };
foreach (int i in fibarray)
{
System.Console.WriteLine(i);
}
Run Code Online (Sandbox Code Playgroud)
您也可以使用它来遍历List<T>集合,如下所示:
List<string> list = new List<string>();
foreach (string item in list)
{
Console.WriteLine(item);
}
Run Code Online (Sandbox Code Playgroud)