gpt4 book ai didi

c# - 实现 ICollection 时无法同时实现 GetEnumerator 返回 IEnumerator 和 IEnumerator

转载 作者:行者123 更新时间:2023-12-03 00:12:48 26 4
gpt4 key购买 nike

我正在编写一个简单的集合类,它实现 ICollection<T> 。一切基本上都有效,除非我添加 IEnumerator<T> GetEnumerator()它提示我没有 IEnumerator GetEnumerator() 的方法方法。反之亦然。我不允许同时拥有两者,因为它们仅在返回类型上有所不同,所以我真的很困惑编译器想要从我这里得到什么。

以下是我收到的错误:

error CS0738: MyClass<T>' does not implement interface memberSystem.Collections.Generic.IEnumerable.GetEnumerator()' and the best implementing candidate MyClass<T>.GetEnumerator()' return typeSystem.Collections.IEnumerator' does not match interface member return type `System.Collections.Generic.IEnumerator'

或者,我也可以:

error CS0738: MyClass<T>' does not implement interface memberSystem.Collections.IEnumerable.GetEnumerator()' and the best implementing candidate MyClass<T>.GetEnumerator()' return typeSystem.Collections.Generic.IEnumerator' does not match interface member return type `System.Collections.IEnumerator'

最佳答案

明确地实现它们:

IEnumerator IEnumerable.GetEnumerator() {
}

IEnumerator<T> IEnumerable<T>.GetEnumerator() {
}

// etc.

显式接口(interface)实现是实现这一点的方式。在 MSDN 上阅读相关信息:http://msdn.microsoft.com/en-us/library/aa288461(v=vs.71).aspx

关于c# - 实现 ICollection<T> 时无法同时实现 GetEnumerator 返回 IEnumerator 和 IEnumerator<T>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19417756/

26 4 0