Enumerator для своей шаблонной коллекции - C#
Формулировка задачи:
Доброго времени суток. Прошу подтолкнуть, подсказать и всячески помочь начинающему.
Есть шаблонный контейнер, необходимо реализовать нумератор для использования контейнера в foreach. Подскажите что-нибудь
class Container<T>
{
private T[] mas;
private int capacity; //ВМЕСТИМОСТЬ КОЛЛЕКЦИИ
private Int32 count; //РЕАЛЬНЫЙ РАЗМЕР
public T this[int index] //ИНДЕКСАТОР
{
get
{
if (index <= mas.Length)
return mas[index];
else
throw new ArgumentOutOfRangeException();
}
set
{
if (index <= mas.Length)
mas[index] = (T)value;
else
throw new ArgumentOutOfRangeException();
}
}
public Int32 Count //КОЛИЧЕСТВО ЭЛЕМЕНТОВ
{
get
{
return count;
}
}
public int Capacity //ВМЕСТИМОСТЬ
{
get { return capacity; }
}
public Container()
{
capacity = 35;
mas = new T[35];
}
public override string ToString() //TOSTRING
{
string s = new string('\r',1);
for (int i = 0; i < count; i++)
{
if (mas[i] != null)
s += mas[i].ToString() + '\n';
}
s += '\n';
return s;
}
public void Add(T elem) //ДОБАВИТЬ В КОЛЛЕКЦИЮ
{
if (count < capacity)
mas[count++] = elem;
else // если заполнился - увеличиваем коллекцию
{
T[] mas2 = new T[capacity*2];
mas.CopyTo(mas2, 0);
mas = mas2;
}
capacity*=2;
}
public T LastAdded() //ПОСЛЕДНИЙ ЭЛЕМЕНТ
{
return mas[count - 1];
}
public void Delete(int index) //УДАЛЯЕТ И-ТЫЙ ЭЛЕМЕНТ
{
if (index < count)
{
for (int i = index; index < count; index++)
mas[i] = mas[i + 1];
count--;
}
}
public MyEnumerator GetEnumerator() //НУМЕРАТОР
{
return new MyEnumerator(this);
}
} public class MyEnumerator
{
int indexEnum;
Container<TElement> coll; //подчеркивает тип, как неизвестный. что необходимо сделать, чтоб можно было создать нумератор для шаблонной коллекции?
public MyEnumerator(Container<TElement> col)
{
this.coll = col;
indexEnum = -1;
}
public bool MoveNext()
{
indexEnum++; // перемещаемся дальше
return (indexEnum < this.coll.mas.GetLength(0));
}
public int Current
{
get
{
return (this.coll.mas[indexEnum]);
}
}
}Решение задачи: «Enumerator для своей шаблонной коллекции»
textual
Листинг программы
class Container<T> : IEnumerable<T>
{
private T[] mas;
private int capacity; //ВМЕСТИМОСТЬ КОЛЛЕКЦИИ
private Int32 count; //РЕАЛЬНЫЙ РАЗМЕР
public T this[int index] //ИНДЕКСАТОР
{
get
{
if (index <= mas.Length)
return mas[index];
else
throw new ArgumentOutOfRangeException();
}
set
{
if (index <= mas.Length)
mas[index] = (T)value;
else
throw new ArgumentOutOfRangeException();
}
}
public Int32 Count //КОЛИЧЕСТВО ЭЛЕМЕНТОВ
{
get
{
return count;
}
}
public int Capacity //ВМЕСТИМОСТЬ
{
get { return capacity; }
}
public Container()
{
capacity = 35;
mas = new T[35];
}
public override string ToString() //TOSTRING
{
string s = new string('\r', 1);
for (int i = 0; i < count; i++) {
if (mas[i] != null)
s += mas[i].ToString() + '\n';
}
s += '\n';
return s;
}
public void Add(T elem) //ДОБАВИТЬ В КОЛЛЕКЦИЮ
{
if (count < capacity)
mas[count++] = elem;
else // если заполнился - увеличиваем коллекцию
{
T[] mas2 = new T[capacity * 2];
mas.CopyTo(mas2, 0);
mas = mas2;
}
capacity *= 2;
}
public T LastAdded() //ПОСЛЕДНИЙ ЭЛЕМЕНТ
{
return mas[count - 1];
}
public void Delete(int index) //УДАЛЯЕТ И-ТЫЙ ЭЛЕМЕНТ
{
if (index < count) {
for (int i = index; index < count; index++)
mas[i] = mas[i + 1];
count--;
}
}
public IEnumerator<T> GetEnumerator() //НУМЕРАТОР
{
return new MyEnumerator(this);
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
private class MyEnumerator : IEnumerator<T>
{
int indexEnum;
Container<T> coll;
public MyEnumerator(Container<T> col)
{
this.coll = col;
indexEnum = -1;
}
public T Current
{
get { return (this.coll.mas[indexEnum]); }
}
public bool MoveNext()
{
indexEnum++; // перемещаемся дальше
return (indexEnum < this.coll.mas.GetLength(0));
}
public void Dispose()
{
}
object IEnumerator.Current
{
get { return Current; }
}
public void Reset()
{
indexEnum = 0;
}
}
}