Deep dive into foreach loops in C#: Which classes can be used?
The foreach loop in C# is an essential feature that allows programmers to easily iterate over elements in a collection. However, understanding which classes can use foreach loops is critical to effective use.
Classes that support foreach loop
Not all classes support foreach loops. Only classes that meet certain conditions can use the foreach loop. According to the answer, the key is that there is a public GetEnumerator()
method in the class. This method should return an object with bool MoveNext()
methods and Current
properties of type T .
Common implementation methods
Actually, the more common interpretation of this requirement is to implement the IEnumerable
/IEnumerable<T>
interface. These interfaces require the presence of IEnumerator
/IEnumerator<T>
respectively.
Supported data structures
Classes that implement the ICollection
/ICollection<T>
interface also implicitly support foreach loops. This includes standard collection types such as Collection<T>
, List<T>
, and arrays (T[]). Therefore, most commonly used "data collections" can be traversed using a foreach loop.
How the foreach loop works
A foreach loop, such as foreach (int i in obj) { ... }
, internally looks like the following code structure:
<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>
Variations and Notes
IDisposable
, it will be called like a using
block to ensure proper disposal. int i
) was placed outside the loop body; starting from C# 5.0, it is declared inside the loop body. This distinction becomes important when using loop variables within nested anonymous methods or lambda expressions. The above is the detailed content of What Classes in C# Support Foreach Loops?. For more information, please follow other related articles on the PHP Chinese website!