什么时候需要分别实现IEnumerator< T>?什么时候、IEnumerator、GT、LT

2023-09-04 13:04:38 作者:醉挽清风

在收藏我经常看见框架类的IEnumerator< T> 分别实现为一个内部类和它的一个实例在的GetEnumerator 方法。

现在假设我写这将有一个内置的集合,比如名单,其中我自己的集合类; T> T [] 充当内部的持有人,说是这样的:

 公共类SpecialCollection< T> :IEnumerable的< T>
{
    名单< T>清单;

    公共SpecialCollection< T>()
    {

    }

    公众的IEnumerator< T>的GetEnumerator()
    {
        返回list.GetEnumerator();

        //要么
        返回list.Where(X =>一些逻辑).GetEnumerator();

        //或者直接依赖于产量关键字
        产量返回X; //等等
    }
}
 
驱动软件无法识别 GT 710显卡

我应该写我自己的枚举器类,还是确定返回名单,其中的枚举器; T> 类?是否有下,我应该写我自己的枚举器类的任何情况?

我有一个相关的问题也是如此。如果它不是那么重要或没有太大的差别,为什么在BCL每一个集合类自己写的IEnumerator

有关,例如,名单,其中,T> 类有类似

  T []项目;
公众的IEnumerator< T>的GetEnumerator()
{
    返回新的List< T> .Enumerator(项目);
}
 

解决方案

回答你的第一个问题是:当收益回报不能满足您的需求。

回答你的第二个问题是:这些频繁使用的类型必须是异常严格的性能要求,所以调查员被定制。我已经写了这方面的一些最近的文章;见:

http://ericlippert.com/2014/05/21/enumerator-advance /

http://ericlippert.com/2014/06/04/enumerator-bounds /

In the framework classes of collections I have often seen IEnumerator<T> separately implemented as an inner class and an instance of it is returned in the GetEnumerator method.

Now suppose I'm writing my own collection classes which will have an inbuilt collection like List<T> or T[] act as the holder internally, say like this:

public class SpecialCollection<T> : IEnumerable<T>
{
    List<T> list;

    public SpecialCollection<T>()
    {

    }

    public IEnumerator<T> GetEnumerator()
    {
        return list.GetEnumerator();

        //or
        return list.Where(x => some logic).GetEnumerator(); 

        //or directly rely on yield keyword
        yield return x; //etc
    }
}

Should I be writing my own enumerator class, or is it ok to return enumerator of the List<T> class? Is there any circumstance under which should I be writing my own enumerator class?

I have a related question as well. If it's not all that important or doesn't make much of a difference, why do every collection class in the BCL write their own IEnumerator?

For eg, List<T> class has something like

T[] items;
public IEnumerator<T> GetEnumerator()
{
    return new List<T>.Enumerator(items);
}

解决方案

The answer to your first question is: when a yield return doesn't meet your needs.

The answer to your second question is: these heavily used types have performance requirements that are unusually strict, so the enumerators are custom built. I've written some articles on this recently; see:

http://ericlippert.com/2014/05/21/enumerator-advance/

http://ericlippert.com/2014/06/04/enumerator-bounds/