Witam, uczę się języka C#, stanąłem na kolekcjach i poznaje podstawowe interfejsy. Dla treningu postanowiłem zaimplementować wspomniany interfejs, oto mój kod:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
class MyList<T> : IEnumerable<T>, IEnumerator<T>
{
private List<T> list;
private int offset = -1;
public MyList()
{
list = new List<T>();
}
private MyList(List<T> l)
{
list = l;
}
public void Add(T item)
{
list.Add(item);
}
public IEnumerator<T> GetEnumerator()
{
return new MyList<T>(list);
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public bool MoveNext()
{
if (offset + 1 >= list.Count) return false;
else
{
offset++;
return true;
}
}
public T Current
{
get { return list[offset]; }
}
object System.Collections.IEnumerator.Current
{
get { return Current; }
}
public void Reset()
{
offset = -1;
}
public void Dispose() { }
}
class Program
{
static void Main(string[] args)
{
MyList<int> ints = new MyList<int>();
ints.Add(1);
ints.Add(2);
ints.Add(3);
ints.Add(4);
ints.Add(5);
foreach (int i in ints)
{
Console.WriteLine(i);
}
Console.ReadLine();
}
}
}
Moje pytanie: Czy dobrze to zrobiłem? Czy tak się robi że klasa kolekcji implementuje zarówno interfejs IEnumerable i IEnumerator i w metodzie GetEnumerator() zwraca nowy obiekt danej klasy? Czy jest jakiś wzorzec jak to powinno się robić? Czy można zrobić to lepiej?