我收到此错误消息,但我不明白为什么!
Error 1 'Exo5Chap12.ShortCollection<T>' does not implement interface member
'System.Collections.IEnumerable.GetEnumerator()'.
'Exo5Chap12.ShortCollection<T>.GetEnumerator()' cannot implement
'System.Collections.IEnumerable.GetEnumerator()' because it does not have the matching
return type of 'System.Collections.IEnumerator'.
E:\MyFolders\Dev\c#\Chapter12\Exo5Chap12\Exo5Chap12\exo5.cs 9 18 Exo5Chap12
这是实现 GetEnumerator() 的代码。 怎么了?
public class ShortCollection<T> : IList<T>
{
protected Collection<T> innerCollection;
protected int maxSize = 10;
public IEnumerator<T> GetEnumerator()
{
return (innerCollection as IEnumerator<T>).GetEnumerator();
}
}
最佳答案
正如其他人所说,您需要实现 IEnumerable
以及IEnumerable<T>
.然而,由于 IEnumberable<T>
本身实现 IEnumerable
这很简单,只需调用您的通用 GetEnumerator()
:
public class ShortCollection<T> : IList<T>
{
protected Collection<T> innerCollection;
protected int maxSize = 10;
public IEnumerator<T> GetEnumerator()
{
return innerCollection.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
我假设您有实际添加和删除 innerCollection
的方法为简洁起见,将它们排除在外,因为它们与手头的问题无关。
关于c# - 有关 IEnumerable.GetEnumerator() 的错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2981615/