关于想使用foreach
必须现实GetEnumerator()方法
static void Main(string[] args)
{
M<int> m = new M<int>();
for (int i = 0; i < 10; i++)
{
m.Add(i);
}
foreach (var item in m)
{
Console.WriteLine(item);
}
Console.ReadKey();
}
class M<T> : IEnumerable
{
int _size = 0;
int max = 0;
T[] x = new T[0];
public T this[int index]
{
get
{
return x[index];
}
set
{
x[index] = value;
}
}
public void Add(T value)
{
if (_size == x.Length)
{
max= x.Length == 0 ? 4 : (x.Length * 2);
T[] tt = new T[_size];
x.CopyTo(tt, 0);
x = new T[max];
tt.CopyTo(x, 0);
}
x[_size++] = value;
}
public int Count
{
get
{
return _size;
}
}
public IEnumerator GetEnumerator()
{
return new MM<T>(x,_size);
}
}
class MM<T> : IEnumerator
{
int _index = -1;
T[] xx;
int _size;
public MM(T[] x,int size)
{
xx = x;
_size = size;
}
public object Current
{
get
{
return xx[_index];
}
}
public bool MoveNext()
{
if (_index >= _size - 1)
{
return false;
}
else
{
_index++;
return true;
}
}
public void Reset()
{
_index = -1;
}
}