如何foreach循环在C#中工作? [英] How do foreach loops work in C#?
问题描述
哪些类型的类可以使用的foreach
循环?
Which types of classes can use foreach
loops?
推荐答案
其实,严格来讲,你需要使用的foreach
是一个返回以东西BOOL的MoveNext()
方法和公共
属性。然而,最通用这个意思是东西器具的GetEnumerator()
的方法?目前{获得;} 的IEnumerable
/ 的IEnumerable< T>
,返回一个的IEnumerator
/ 的IEnumerator< T>
Actually, strictly speaking, all you need to use foreach
is a public GetEnumerator()
method that returns something with a bool MoveNext()
method and a ? Current {get;}
property. However, the most common meaning of this is "something that implements IEnumerable
/IEnumerable<T>
, returning an IEnumerator
/IEnumerator<T>
.
这意味着,这包括任何实现的ICollection
/ 的ICollection&LT; T&GT;
,比如像什么收藏&LT; T&GT;
,列表&LT; T&GT;
,阵列( T []
)等,所以任何标准数据集一般会支持的foreach
。
By implication, this includes anything that implements ICollection
/ICollection<T>
, such as anything like Collection<T>
, List<T>
, arrays (T[]
), etc. So any standard "collection of data" will generally support foreach
.
有关第一点的证明,下面工作得很好:
For proof of the first point, the following works just fine:
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);
}
}
}
如何工作的?
一个foreach循环就像的foreach(INT我的obj){...}
有点儿等同于:
A foreach loop like foreach(int i in obj) {...}
kinda equates to:
var tmp = obj.GetEnumerator();
int i; // up to C# 4.0
while(tmp.MoveNext()) {
int i; // C# 5.0
i = tmp.Current;
{...} // your code
}
但是,也有变化。例如,它枚举(TMP)支持的IDisposable
,它(使用类似于)使用了。
However, there are variations. For example, it the enumerator (tmp) supports IDisposable
, it is used too (similar to using
).
注意在声明的位置差异 INT I
的在的(C#5.0)与的之外的(高达C#4.0)的循环。如果您在code块内的匿名方法/λ使用 I
这一点很重要。但是,这是另一个故事;-p
Note the difference in the placement of the declaration "int i
" inside (C# 5.0) vs. outside (up C# 4.0) the loop. It's important if you use i
in an anonymous method/lambda inside your code-block. But that is another story ;-p
这篇关于如何foreach循环在C#中工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!