foreach loop in C#
Q: Which object types support foreach loop?
Answer: The core use of the foreach
loop requires a MoveNext()
method that returns an object with a Current
method and a GetEnumerator()
property. Simply put, the most common types are those that implement IEnumerable
/IEnumerable<T>
. This includes implementations of ICollection
/ICollection<T>
, such as Collection<T>
, List<T>
, arrays, etc.
How does it work?
A foreach(int i in obj) {...}
loop of the form foreach
is essentially equivalent to:
<code class="language-csharp">var tmp = obj.GetEnumerator(); int i; // C# 4.0及之前版本 while(tmp.MoveNext()) { int i; // C# 5.0及之后版本 i = tmp.Current; {...} // 你的代码 }</code>
IEnumerator
object (tmp
) is used to iterate over the elements of the collection and assign them to the loop variable on each iteration. If the enumerator supports the Dispose()
method, it is called just like using the using
statement.
Note: The location of the loop variable declaration "int i
" differs between C# 4.0 and C# 5.0. C# 5.0 declares it inside the loop, while C# 4.0 declares it outside the loop. This distinction is important when using loop variables in closures or lambda expressions within loops.
The above is the detailed content of Which C# Object Types Support foreach Loops and How Do They Work?. For more information, please follow other related articles on the PHP Chinese website!