c#-foreach的秘密
foreach的秘密
class Program
{
static void Main(string[] args)
{
//创建Person的对象
Person p1=new Person();
//遍历p1因为实现了IEnumerable接口
foreach (var item in p1)
{
Console.WriteLine(item);
}
Console.ReadKey();
}
}
//实现了Ienumerable接口就可以遍历对象了
//实现IIndextor因为EnumeratorIndex是泛型类需要实现IIndextor接口
public class Person:IEnumerable,IIndextor
{
public string[] strs = new string[6];
public string this[int Index]
{
get { return strs[Index]; }
set { strs[Index] = value; }
}
public Person()
{
strs[0] = "3sfgew";
strs[1] = "322";
strs[2] = "34";
strs[3] = "3434";
strs[4] = "3ww";
strs[5] = "3sdfe";
}
public IEnumerator GetEnumerator()
{
//返回Ienumerator的实现类
return new EnumeratorIndex<Person>(this);
}
public int IndexLength
{
get { return strs.Length; }
}
}
//定义索引器的接口
public interface IIndextor
{
string this[int Index] { get; }
int IndexLength { get; }
}
public class EnumeratorIndex<T> : IEnumerator where T:IIndextor
{
T p1;
int Index;
//构造函数
public EnumeratorIndex(T p1)
{
//给必须的对象赋值
//Index的初始值必须是-1
Index = -1;
this.p1 = p1;
}
//返回当前的对象
public object Current
{
get { return p1[Index]; }
}
//使索引前进到下一个
public bool MoveNext()
{
if (Index < p1.IndexLength - 1)
{
Index++;
return true;
}
else
{
return false;
}
}
//初始化索引
public void Reset()
{
Index = -1;
}
}