我正在尝试创建一个包装器Dictionary<String,Foo>
.
Dictionary<String,Foo>
实施IEnumerable<KeyValuePair<String,Foo>>
,但我希望我的包装类实现IEnumerable<Foo>
。所以我尝试了这个:
public class FooCollection : IEnumerable<Foo>
{
private Dictionary<string, Foo> fooDictionary = new Dictionary<string, Foo>();
public IEnumerator<Foo> GetEnumerator()
{
return fooDictionary.Values.GetEnumerator();
}
// Other wrapper methods omitted
}
但是我收到这个错误:
'FooCollection' does not implement interface member 'System.Collections.IEnumerable.GetEnumerator()'. 'FooCollection.GetEnumerator()' cannot implement 'System.Collections.IEnumerable.GetEnumerator()' because it does not have the matching return type of 'System.Collections.IEnumerator'.
但是我不明白这个错误,因为FooCollection.GetEnumerator()
返回一个IEnumerator<Foo>
, and IEnumerator<Foo>
is an IEnumerator
.
EDIT:
显式实现的解决方案IEnumerator.GetEnumerator()
作品。然而我现在想知道为什么当我“转到定义”时List<T>
我只看到 GetEnumerator 的一个定义:public List<T>.Enumerator GetEnumerator();
显然List<T>
可以有一个GetEnumerator
返回实现两者的方法IEnumerator<T>
and IEnumerator
,但我必须为每个方法都有一种方法?
EDIT:
正如 LukeH 在下面的回答,List<T>
does包括显式接口实现。显然,当从元数据生成方法存根时,Visual Studio 并没有列出这些内容。 (参见上一个问题:为什么VS元数据视图不显示显式接口实现的成员 https://stackoverflow.com/questions/7268632/why-does-the-vs-metadata-view-does-not-display-explicit-interface-implemented-mem )
在发布这个问题之前我曾尝试检查List<T>
(通过 Visual Studio 中的“转到定义”)查看是否需要实现多个版本的 GetEnumerator。我想这不是最可靠的检查方法。
无论如何,我将其标记为已回答。感谢您的帮助。