这段代码没有编译,它抛出了以下错误:
类型“TestesInterfaces.MyCollection”已经包含了“当前”的定义
但是当我删除这个不明确的方法时,它会继续给出其他错误。
有人能帮忙吗?
public class MyCollection<T> : IEnumerator<T>
{
private T[] vector = new T[1000];
private int actualIndex;
public void Add(T elemento)
{
this.vector[vector.Length] = elemento;
}
public bool MoveNext()
{
actualIndex++;
return (vector.Length > actualIndex);
}
public void Reset()
{
actualIndex = -1;
}
void IDisposable.Dispose() { }
public Object Current
{
get
{
return Current;
}
}
public T Current
{
get
{
try
{
T element = vector[actualIndex];
return element;
}
catch (IndexOutOfRangeException e)
{
throw new InvalidOperationException(e.Message);
}
}
}
}发布于 2013-08-07 13:46:31
我想你误解了IEnumerator<T>。通常,集合实现IEnumerable<T>,而不是IEnumerator<T>。你可以这样想:
IEnumerable<T>时,它表示"I是可以枚举的事物的集合“。IEnumerator<T>时,它是在声明"I是一个对某事物进行枚举的事物“。集合实现IEnumerator<T>的情况很少(而且可能是错误的)。通过这样做,您将集合限制为单个枚举。如果您试图在已经循环通过集合的代码段中循环该集合,或者尝试同时在多个线程上循环该集合,您将无法这样做,因为您的集合本身正在存储枚举操作的状态。通常,集合(实现IEnumerable<T>)返回一个单独的对象(实现IEnumerator<T>),该单独的对象负责存储枚举操作的状态。因此,您可以拥有任意数量的并发或嵌套枚举,因为每个枚举操作都由一个不同的对象表示。
此外,为了使foreach语句工作,in关键字后面的对象必须实现IEnumerable或IEnumerable<T>。如果对象只实现IEnumerator或IEnumerator<T>,它将无法工作。
我相信这就是你要找的密码:
public class MyCollection<T> : IEnumerable<T>
{
private T[] vector = new T[1000];
private int count;
public void Add(T elemento)
{
this.vector[count++] = elemento;
}
public IEnumerator<T> GetEnumerator()
{
return vector.Take(count).GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}发布于 2013-08-07 13:25:52
您需要定义当前正在实现的接口。
Object IEnumerator.Current
{
//
}
public T Current
{
//
}这样,类就有2个Current属性。但你可以同时访问它们。
MyCollection<string> col = new MyCollection<string>();
var ienumeratort = col.Current; //Uses IEnumerator<T>
var ienumerator = (IEnumerator)col.Current; //uses IEnumerator发布于 2018-02-14 18:08:55
我认为,在C# 2.0之后,您有一种非常简单的实现迭代器的方法,编译器通过创建状态机在场景后面做了很多繁重的工作。值得一查。尽管如此,在这种情况下,您的实现如下所示:
public class MyCollection<T>
{
private T[] vector = new T[1000];
private int actualIndex;
public void Add(T elemento)
{
this.vector[vector.Length] = elemento;
}
public IEnumerable<T> CreateEnumerable()
{
for (int index = 0; index < vector.Length; index++)
{
yield return vector[(index + actualIndex)];
}
}
}不过,我不确定actualIndex的目的--但我希望你明白这个想法。
在正确初始化MyCollection之后,下面的代码片段从消费者的角度看有点像:
MyCollection<int> mycoll = new MyCollection<int>();
foreach (var num in mycoll.CreateEnumerable())
{
Console.WriteLine(num);
}https://stackoverflow.com/questions/18104624
复制相似问题