Home >Backend Development >C++ >IEnumerable and IEnumerator in C#: How Do They Enable foreach Loops and Custom Iterators?
In-depth understanding of IEnumerable and IEnumerator: the core mechanism of .NET iterators
In .NET programming, implementing the IEnumerable interface is the key to enabling foreach loops. Although the foreach syntax is concise and easy to use, its underlying dependence is on the IEnumerable and IEnumerator interfaces.
Application scenarios of IEnumerable and IEnumerator
IEnumerable is not used to "replace" foreach; on the contrary, implementing IEnumerable is a prerequisite for using foreach. When you write a foreach loop, the compiler actually converts it into a series of calls to the IEnumerator's MoveNext and Current methods.
The difference between IEnumerable and IEnumerator
Why do we need IEnumerable and IEnumerator?
implements IEnumerable
To make a class iterable, you need to implement the IEnumerable interface, which requires implementing the GetEnumerator method that returns an IEnumerator.
Example
Consider the following custom object class that implements the IEnumerable interface:
<code class="language-csharp">public class CustomCollection : IEnumerable<int> { private int[] data; public IEnumerator<int> GetEnumerator() { return new CustomEnumerator(data); } IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } private class CustomEnumerator : IEnumerator<int> { // MoveNext 和 Current 方法用于遍历 data } }</code>
By implementing IEnumerable and providing a custom enumerator, you can now use a foreach loop to iterate over instances of a CustomCollection.
The above is the detailed content of IEnumerable and IEnumerator in C#: How Do They Enable foreach Loops and Custom Iterators?. For more information, please follow other related articles on the PHP Chinese website!