Общие Коллекции C#
Я реализовал универсальный пользовательский класс коллекции, который принимает только объект типа Person.
Предоставляя поддержку перечислителя для перебора коллекции, он показывает ошибку
Невозможно применить индексирование с помощью [] к выражению типа 'CustomCollection.CustomCollection'
Ниже приведен фрагмент кода для класса, который я создал.
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 в качестве свойств.
2 ответа
ICollection не реализует индексатор. Если вы хотите использовать индексирование, вы должны вместо этого реализовать IList.
Ты можешь использовать Linq
с ICollection
:
var result = Items.ElementAt(index);
Или вы можете добавить свой собственный индексатор:
public T this[int i]
{
return Items[i];
}
Чтобы создать код, вам нужно добавить индексаторCustomCollection<T>
класс, например
public T this[int index]
{
return lst [index];
}
Тогда вы можете сказать, использовать collection[n]
чтобы получить n-й элемент в MoveNext()
метод.
Или же
Вместо того, чтобы иметь PersonEnumerator<T>
класс вы могли бы просто выставить lst.GetEnumerator()
который возвращает IEnumerator<T>
т.е.
public IEnumerator<T> GetEnumerator()
{
return lst.GetEnumerator();
}
Если вы не планируете делать что-то необычное со своим перечислителем, вы можете использовать тот же для lst
,