故障实现IEnumerable的&LT; T&GT; [英] Troubles implementing IEnumerable<T>
问题描述
我试图写我自己的(简单)List实现。这是我做的,到目前为止:
I'm trying to write my own (simple) implementation of List. This is what I did so far:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace provaIEnum
{
class MyList<T> : IEnumerable<T>
{
private T[] _array;
public int Count { get; private set; }
public MyList() { /* ... */ }
public void Add(T element) { /* ... */ }
// ...
public IEnumerator<T> GetEnumerator()
{
for (int i = 0; i < Count; i++)
yield return _array[i];
}
}
我收到有关的GetEnumerator的错误,但:
I'm getting an error about GetEnumerator though:
provaIEnum.Lista不实现接口成员
System.Collections.IEnumerable.GetEnumerator()。
provaIEnum.Lista.GetEnumerator()无法实现
System.Collections.IEnumerable.GetEnumerator()',因为它不
有System.Collections.IEnumerator'匹配的返回类型。
'provaIEnum.Lista' does not implement interface member 'System.Collections.IEnumerable.GetEnumerator()'. 'provaIEnum.Lista.GetEnumerator()' cannot implement 'System.Collections.IEnumerable.GetEnumerator()' because it does not have the matching return type of 'System.Collections.IEnumerator'.
我不知道如果我理解VS的想告诉我,我不知道如何解决它。
I'm not sure if I understand what VS's trying to tell me and I have no idea how to fix it.
感谢您的时间
推荐答案
IEnumerable的&LT; T&GT;
工具<一个href=\"http://msdn.microsoft.com/en-us/library/system.collections.ienumerable.aspx\"><$c$c>IEnumerable$c$c>你需要实现这个接口,以及在你的类拥有的非通用版本<一个href=\"http://msdn.microsoft.com/en-us/library/system.collections.ienumerable.getenumerator.aspx\">GetEnumerator方法。为了避免冲突,你可以明确地实现它:
Since IEnumerable<T>
implements IEnumerable
you need to implement this interface as well in your class which has the non-generic version of the GetEnumerator method. To avoid conflicts you could implement it explicitly:
IEnumerator IEnumerable.GetEnumerator()
{
// call the generic version of the method
return this.GetEnumerator();
}
public IEnumerator<T> GetEnumerator()
{
for (int i = 0; i < Count; i++)
yield return _array[i];
}
这篇关于故障实现IEnumerable的&LT; T&GT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!