【问题标题】:IDictionaryEnumerator is not an iterator interface type?IDictionaryEnumerator 不是迭代器接口类型?
【发布时间】:2013-09-24 09:45:31
【问题描述】:

我正在尝试将一些使用Hashtable 的代码移植到没有此类的环境中。所以我考虑不要乱写代码,只需从Dictionary 创建我自己的Hashtable,如下所示:

public class Hashtable : Dictionary<Object, Object> {
    // ...
    new public IDictionaryEnumerator GetEnumerator() {          

      var ie = base.GetEnumerator();
      while (ie.MoveNext())
          yield return new DictionaryEntry(ie.Current.Key, ie.Current.Value);
    }
}

我收到此错误:

错误 CS1624:“System.Collections.Hashtable.GetEnumerator()”的主体不能是迭代器块,因为“System.Collections.IDictionaryEnumerator”不是迭代器接口类型

好吧,但是 IDictionaryEnumerator 继承自 IEnumerator。

奇怪的是,如果我只返回 (IDictionaryEnumerator)base.GetEnumerator();,代码就会编译(但在 foreach 循环中运行时失败)。

我不明白这个错误告诉我什么,也不知道如何正确实施。

【问题讨论】:

标签: c# collections yield ienumerator


【解决方案1】:

编译器将迭代器块重写为实现IEnumerable或IEnumerator的类;编译器不知道如何生成实现IDictionaryEnumerator 的类,因此您不能使用迭代器块来实现该接口。

一种可能的解决方法是提供您自己的IDictionaryEnumerator 实现:

class Hashtable : Dictionary<object, object>
{
    new public IDictionaryEnumerator GetEnumerator()
    {
        return new DictionaryEnumerator(base.GetEnumerator());
    }

    struct DictionaryEnumerator : IDictionaryEnumerator
    {
        private Enumerator _en;

        public DictionaryEnumerator(Dictionary<object, object>.Enumerator en)
        {
            _en = en;
        }

        public object Current
        {
            get
            {
                return Entry;
            }
        }

        public DictionaryEntry Entry
        {
            get
            {
                var kvp = _en.Current;
                return new DictionaryEntry(kvp.Key, kvp.Value);
            }
        }

        public bool MoveNext()
        {
            bool result = _en.MoveNext();
            return result;
        }

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

        public object Key
        {
            get
            {
                var kvp = _en.Current;
                return kvp.Key;
            }
        }

        public object Value
        {
            get
            {
                var kvp = _en.Current;
                return kvp.Value;
            }
        }
    }
}

【讨论】:

    猜你喜欢
    • 2014-09-22
    • 1970-01-01
    • 1970-01-01
    • 2022-01-10
    • 2014-02-02
    • 2019-07-09
    • 2013-02-28
    • 2019-06-04
    • 2012-05-24
    相关资源
    最近更新 更多