首页 > 代码库 > 枚举 IEnumerable
枚举 IEnumerable
namespace _03
{
class Program
{
public static void Main()
{
Person person = new Person();
IEnumerator ienu= person.GetEnumerator();
while (ienu.MoveNext())
{
Console.WriteLine(ienu.Current);
}
}
}
class Person :IEnumerable // 返回一个循环访问集合的枚举数
{
private string[] _names = { "夹心饼干","大师","香肠"};
private string _email;
private int _age;
public int Age
{
get { return _age; }
set { _age = value; }
}
public string Email
{
get
{ return _email; }
set
{ _email = value; }
}
public string[] Names
{
get { return _names; }
set { _names = value; }
}
private string _name;
public string Name
{
get { return _name; }
set { _name = value; }
}
// 一个可用于循环访问集合的 System.Collections.IEnumerator 对象。
public IEnumerator GetEnumerator()
{
return new Person1(Names);
}
}
class Person1:IEnumerator
{
public Person1(string[] names)
{
_names = names;
}
public Person1() { }
private string[] _names;
public string[] Names
{
get { return _names; }
set { _names = value; }
}
private int index = -1;
public int Index
{
get { return index; }
set { index = value; }
}
public string this[int index]
{
get { return this[index]; }
}
public object Current
{
get
{
if(Index<Names.Length&&Index>=0)
{
return Names[Index];
}
else
{
throw new IndexOutOfRangeException();
}
}
}
public bool MoveNext()
{
if (index+1<Names.Length)
{
index++;
return true;
}
return false;
}
public void Reset()
{
index = -1;
}
}
}
枚举 IEnumerable