我们将如何实现IEnumerator接口?

时间:2020-03-05 18:50:42  来源:igfitidea点击:

我有一个将对象映射到对象的类,但与字典不同的是,它以两种方式映射它们。我现在正在尝试实现一个自定义IEnumerator接口,该接口迭代这些值。

public class Mapper<K,T> : IEnumerable<T>, IEnumerator<T>

{
    C5.TreeDictionary<K,T> KToTMap = new TreeDictionary<K,T>();
    C5.HashDictionary<T,K> TToKMap = new HashDictionary<T,K>();

    public void Add(K key, T value)
    {
        KToTMap.Add(key, value);
        TToKMap.Add(value, key);

    }

    public int Count
    {
        get { return KToTMap.Count; }
    }

    public K this[T obj]
    {
        get
        {
            return TToKMap[obj];
        }
    }

    public T this[K obj]
    {
        get
        {
            return KToTMap[obj];
        }
    }

    public IEnumerator<T> GetEnumerator()
    {
        return KToTMap.Values.GetEnumerator();
    }

    public T Current
    {
        get { throw new NotImplementedException(); }
    }

    public void Dispose()
    {
        throw new NotImplementedException();
    }

    object System.Collections.IEnumerator.Current
    {
        get { throw new NotImplementedException(); }
    }

    public bool MoveNext()
    {
        ;
    }

    public void Reset()
    {
        throw new NotImplementedException();
    }
}

解决方案

回答

使用收益率回报。

C#中使用的yield关键字是什么?

回答

只需实现IEnumerable接口,就无需实现IEnumerator,除非我们想在枚举器中做一些特殊的事情,这对于情况似乎是不需要的。

public class Mapper<K,T> : IEnumerable<T> {
    public IEnumerator<T> GetEnumerator()
    {
        return KToTMap.Values.GetEnumerator();
    }
}

就是这样。

回答

首先,不要使集合对象实现IEnumerator <>。这会导致错误。 (考虑两个线程在同一个集合上进行迭代的情况)。

正确实现枚举数并非易事,因此C2.0基于'yield return'语句添加了特殊的语言支持。

Raymond Chen最近的一系列博客文章("在Cand中实现迭代器会导致后果")是一个快速入门的好地方。

  • 第1部分:http://blogs.msdn.com/oldnewthing/archive/2008/08/12/8849519.aspx
  • 第2部分:http://blogs.msdn.com/oldnewthing/archive/2008/08/13/8854601.aspx
  • 第3部分:http://blogs.msdn.com/oldnewthing/archive/2008/08/14/8862242.aspx
  • 第4部分:http://blogs.msdn.com/oldnewthing/archive/2008/08/15/8868267.aspx