简体   繁体   中英

Where are the methods from the IEnumerable interface implemented for built in classes of the MSDN?

I've been searching in the MSDN to try to see a class in which the methods from IEnumerator are implemented. For example, the ArrayList class. Is it possible to visualize the helper class in which the IEnumerator interface is implemented so that the GetEnumerator() from IEnumerable interface is able to return an instance of this class and the foreach functionality becomes available? I realize that there is no practical use of this. This would be only for "academic" purpouses, to better understand how the developers from the language built it.

ArrayList is considered to be an integral part of the platform, so you may not necessarily find it where you think it should be. (It is also obsolete, and you should prefer a generic collection such as List<T> .) For example, in .NET, it is not defined in the collections solution, but rather in mscorlib , in mscorlib/system/collections/arraylist.cs . The definition of GetEnumerator is essentially just a single line:

return new ArrayListEnumeratorSimple(this);

There is also an overload which iterates over a sublist , which is again essentially a single line:

return new ArrayListEnumerator(this, index, count);

The definition of ArrayListEnumerator is again rather simple, if you strip out argument validation and such, it is basically just:

public bool MoveNext() {
    if (index < endIndex) {
        currentElement = list[++index];
        return true;
    }
    else {
        index = endIndex + 1;
    }

    return false;
}

public Object Current => currentElement;

The definition of ArrayListEnumeratorSimple is ironically more complex, but still essentially the same.

Note that the .NET source code is quite old, and ArrayList is one of the oldest classes in there.

For a more modern perspective, you could look at CoreFX's implementation in src/System.Runtime.Extensions/src/System/Collections/ArrayList.cs , but apart from a more modern coding style, and the use of a sentinel value instead of null , it is exactly the same.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM