What is the usage of IEnumerable in C#?

In C#, IEnumerable is an interface that represents the type capable of being enumerated over a collection. It defines a method GetEnumerator() that returns an object implementing the IEnumerator interface, used to iterate through the elements in the collection.

By using the IEnumerable interface, you can create custom collection classes that can be iterated through using foreach statement. By implementing the GetEnumerator() method, you can return an IEnumerator object which contains the elements in the collection and methods for moving the current position.

Here is an example code using IEnumerable:

public class MyCollection : IEnumerable
{
    private int[] data;

    public MyCollection()
    {
        // 初始化集合数据
        data = new int[] { 1, 2, 3, 4, 5 };
    }

    // 实现IEnumerable接口的GetEnumerator方法
    public IEnumerator GetEnumerator()
    {
        return new MyEnumerator(data);
    }
}

public class MyEnumerator : IEnumerator
{
    private int[] data;
    private int position = -1;

    public MyEnumerator(int[] data)
    {
        this.data = data;
    }

    // 实现IEnumerator接口的MoveNext方法
    public bool MoveNext()
    {
        position++;
        return (position < data.Length);
    }

    // 实现IEnumerator接口的Reset方法
    public void Reset()
    {
        position = -1;
    }

    // 实现IEnumerator接口的Current属性
    public object Current
    {
        get
        {
            return data[position];
        }
    }
}

// 使用自定义的集合类进行遍历
MyCollection collection = new MyCollection();
foreach (int num in collection)
{
    Console.WriteLine(num);
}

In the example above, the MyCollection class implements the IEnumerable interface and returns a MyEnumerator object that implements the IEnumerator interface. This allows the MyCollection object to be iterated through in a foreach loop, printing out its elements.

It is important to note that in C#, there is also a generic version of the IEnumerable interface, which is more commonly used and allows for specifying the type of elements in the collection. The generic version of the IEnumerable interface is similar to the non-generic version, but the returned IEnumerator object is of type IEnumerator and the type of the Current property is also T.

bannerAds