【发布时间】:2015-05-05 02:23:50
【问题描述】:
我已经实现了一个通用的自定义集合类,它只接受一个 Person 类型的对象。
在为 Enumerator 迭代集合提供支持时,它会显示错误
无法将带有 [] 的索引应用于“CustomCollection.CustomCollection”类型的表达式
下面是我创建的类的代码 sn-p。
public class CustomCollection<T> : ICollection<T> where T : Person
{
private IList<T> lst = null;
public CustomCollection()
{
lst = new List<T>();
}
public void Add(T item)
{
this.lst.Add(item);
}
public void Clear()
{
this.lst.Clear();
}
public bool Contains(T item)
{
bool result = false;
foreach (T obj in this.lst)
{
if (obj.Id.Equals(item.Id))
{
result = true;
break;
}
}
return result;
}
public void CopyTo(T[] array, int arrayIndex)
{
throw new NotImplementedException();
}
public int Count
{
get { return this.lst.Count; }
}
public bool IsReadOnly
{
get { return false; }
}
public bool Remove(T item)
{
bool result = false;
foreach (T obj in this.lst)
{
if (obj.Id.Equals(item.Id))
{
this.lst.Remove(item);
}
}
return result;
}
public IEnumerator<T> GetEnumerator()
{
return new PersonEnumerator<T>(this);
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
Enumerator 类如下:
public class PersonEnumerator<T> : IEnumerator<T> where T : Person
{
private CustomCollection<T> collection = null;
private int index;
private T current;
public PersonEnumerator(CustomCollection<T> collection)
{
this.collection = collection;
this.index = -1;
current = default(T);
}
public T Current
{
get { return this.current; }
}
public void Dispose()
{
throw new NotImplementedException();
}
object IEnumerator.Current
{
get { return this.Current; }
}
public bool MoveNext()
{
if (++this.index >= collection.Count)
{
return false;
}
else
{
this.current = collection[this.index];
}
return true;
}
public void Reset()
{
this.index = -1;
current = default(T);
}
}
Person 类仅包含 FirstName、LastName 和 Id 作为属性。
【问题讨论】:
-
您是否缺少自定义集合类中的索引器声明? msdn.microsoft.com/en-us/library/2549tw02.aspx
-
哎呀。错误的链接。给你:stackoverflow.com/questions/424669/…
-
旁注:
public bool Remove(T item)实现包含一个错误:你不能修改一个集合(在你的情况下是this.lst)withing foreach 循环 -
还注意到
IEnumerator.Current在PersonEnumerator<T>内部是错误的。
标签: c# enumerator generic-collections