问题描述
我试图创建一个词典℃的包装;弦乐,富方式>
字典<弦乐,富>
工具的IEnumerable< KeyValuePair<弦乐,富>>
,但我想我的包装类来实现的IEnumerable<富>
。所以,我想这样的:
公共类FooCollection:IEnumerable的<富>
{
私人字典<字符串,富> fooDictionary =新词典<字符串,富>();
公众的IEnumerator<富>的GetEnumerator()
{
返回fooDictionary.Values.GetEnumerator();
}
//其他包装方法省略
}
不过,我得到这个错误:
However I don't understand this error, because FooCollection.GetEnumerator()
returns an IEnumerator<Foo>
, and IEnumerator<Foo>
is an IEnumerator
.
EDIT:
The solution of explicitly implementing IEnumerator.GetEnumerator()
works. However I'm now wondering why when I "Go to definition" on a List<T>
I see only one definition of GetEnumerator:public List<T>.Enumerator GetEnumerator();
Apparently List<T>
can have a single GetEnumerator
method that returns something that implements both IEnumerator<T>
and IEnumerator
, but I have to have one method for each?
EDIT:
As answered by LukeH below, List<T>
does include the explicit interface implementations. Apparently Visual Studio just doesn't list those when generating method stubs from the metadata. (See this previous question: Why does the VS Metadata view does not display explicit interface implemented members )
Before posting this question I had tried checking List<T>
(via "Go to Definition" in Visual Studio) to see if I needed to implement multiple versions of GetEnumerator. I guess this wasn't the most reliable way to check.
Anyway, I'm marking this as answered. Thanks for your help.
Add the following explicit interface implementation:
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
Although IEnumerator<T>
is an IEnumerator
, the contract for IEnumerable
returns an IEnumerator
specifically, not an IEnumerator<T>
这篇关于如何在实现IEnumerable<我的字典包装类实现IEnumerable;美孚> ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!