【发布时间】: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 循环中运行时失败)。
我不明白这个错误告诉我什么,也不知道如何正确实施。
【问题讨论】:
-
需要实现
IEnumerable<T>,而不是IEnumerator。 -
@MatthewWatson:迭代器块的返回类型可以是
IEnumerable、IEnumerable<T>、IEnumerator和IEnumerator<T>:msdn.microsoft.com/en-us/library/vstudio/dscyy5s0.aspx
标签: c# collections yield ienumerator