什么是IEnumerable的.NET中IEnumerable、NET

2023-09-02 20:48:42 作者:萌叔i

什么是IEnumerable的在.net中?

what is IEnumerable in .net?

推荐答案

这是提供的迭代器模式。此外,还有通用的版本,这是的IEnumerable< T>

It's an interface implemented by Collection types in .NET that provide the Iterator pattern. There also the generic version which is IEnumerable<T>.

语法(你很少看到,因为有prettier的方式来做到这一点),通过实现IEnumerable集合移动是:

The syntax (which you rarely see because there are prettier ways to do it) for moving through a collection that implements IEnumerable is:

IEnumerator enumerator = collection.GetEnumerator();

while(enumerator.MoveNext())
{
    object obj = enumerator.Current;
    // work with the object
}

这是functionaly等价于:

Which is functionaly equivalent to:

foreach(object obj in collection)
{
    // work with the object
}

如果集合支持索引器,你也可以遍历其与经典的for循环的方法,但迭代器模式提供了一些不错的演员一样,增加了对线程同步的能力。

If the collection supports indexers, you could also iterate over it with the classic for loop method but the Iterator pattern provides some nice extras like the ability to add synchronization for threading.