List<T>
类实现了 IEnumerable<T>
界面。它有一个方法 GetEnumerator
返回 List<T>.Enumerator
.
我有一个如下所示的类,它给出了一个编译错误,指出 GetEnumerator
的返回类型与接口(interface)不匹配。
public class InsertionSortedSet<T> : IEnumerable<T>
{
public struct Enumerator : IEnumerator<T>
{
// Required interface implemented
}
// Other interface methods implemented
public Enumerator GetEnumerator()
{
return new Enumerator(this);
}
}
'Entities.Helpers.InsertionSortedSet' does not implement interface member 'System.Collections.Generic.IEnumerable.GetEnumerator()'. 'Entities.Helpers.InsertionSortedSet.GetEnumerator()' cannot implement 'System.Collections.Generic.IEnumerable.GetEnumerator()' because it does not have the matching return type of 'System.Collections.Generic.IEnumerator'.
鉴于List<T>
似乎返回它自己的Enumerator
类(不是接口(interface)),但它确实实现了 Enumeration<T>
界面我很困惑,因为我看不出我与那个类(class)有什么不同。
我的设置有什么问题导致它失败,其中 List<T>
有用吗?
我想返回一个 InsertionSortedSet<T>.Enumerator
而不是界面,因为它避免了装箱,我需要将其剪掉。
最佳答案
它在提示,因为 GetEnumerator() 返回 IEnumerator<T>
对于 IEnumerable<T>
界面。为了满足,您的类型必须返回 IEnumerator<T>
(对于 IEnumerator
也是一个明确的)。
但是,很多时候希望类返回比接口(interface)指定的更具体的类型,但接口(interface)不允许这样的协变返回类型。所以要做到这一点,你可以做什么 List<T>
确实有 GetEnumerator()
返回您的特定枚举器,但您还必须为 IEnumerable.GetEnumerator()
实现显式实现返回 IEnumerator
和 IEnumerable<T>.GetEnumerator()
返回 IEnumerator<T>
:
// This is your specific version, like List<T> does
public Enumerator GetEnumerator()
{
return new Enumerator(this);
}
// This is the one with the return value IEnumerator<T> expects
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
return new Enumerator(this);
}
// Plus, it also expects this as well to satisfy IEnumerable
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
如果你看List<T>
你会看到它实现了 GetEnumerator()
三遍:
- 曾经明确表示
IEnumerable<T>
- 曾经明确表示
Enumerable
- 曾经有一个非常特定于列表的返回
如果你愿意,你可以在你的类里面做同样的事情(这应该是你开始的方式)但如果你这样做,你必须明确地实现 IEnumerable<T>.GetEnumerator()
和 IEnumerable.GetEnumerator()
如果您导航到定义,您可以通过选择它满足的不同接口(interface)(或通过将 List<T>
实例分配给 IEnumerable
或 IEnumerable<T>
引用并转到定义来查看对象浏览器中的其他定义):
关于c# - 接口(interface)实现和返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8764919/