代码
//可枚举对象并非必须实现IEnumerable接口。该职责可以委托给第三个类来实现。
public class Persons
{
string[] m_Names;
public Persons(params string[] Names)
{
m_Names = new string[Names.Length];
Names.CopyTo(m_Names, 0);
}
private string this[int index]
{
get { return m_Names[index]; }
set { m_Names[index] = value; }
}
private class PersonsEnumerator : IEnumerator
{
int index = -1;
Persons p;
public PersonsEnumerator(Persons p)
{
this.p = p;
}
public bool MoveNext()
{
index++;
return index < p.m_Names.Length;
}
public void Reset()
{
index = -1;
}
public object Current
{
get
{
return p.m_Names[index];
}
}
}
private class PersonsEnumerable : IEnumerable
{
private Persons m_persons;
internal PersonsEnumerable(Persons persons)
{
m_persons = persons;
}
IEnumerator IEnumerable.GetEnumerator()
{
return new PersonsEnumerator(m_persons);
}
}
public IEnumerable InOrder
{
get { return new PersonsEnumerable(this); }
}
public IEnumerable Reverse
{
get
{
int length=this.m_Names.Length;
Persons persons= new Persons();
persons.m_Names = new string[length];
for (int i = 0; i < length; i++)
{
persons.m_Names[i] = m_Names[length-i-1];
}
return new PersonsEnumerable(persons);
}
}
}
实现代码:
public static void EnumObject()
{
Persons p = new Persons("001","002","003");
//正向输出
foreach (string s in p.InOrder)
{
Console.WriteLine(s);
}
//反序输出
foreach (string s in p.Reverse)
{
Console.WriteLine(s);
}
}
public class Persons
{
string[] m_Names;
public Persons(params string[] Names)
{
m_Names = new string[Names.Length];
Names.CopyTo(m_Names, 0);
}
private string this[int index]
{
get { return m_Names[index]; }
set { m_Names[index] = value; }
}
private class PersonsEnumerator : IEnumerator
{
int index = -1;
Persons p;
public PersonsEnumerator(Persons p)
{
this.p = p;
}
public bool MoveNext()
{
index++;
return index < p.m_Names.Length;
}
public void Reset()
{
index = -1;
}
public object Current
{
get
{
return p.m_Names[index];
}
}
}
private class PersonsEnumerable : IEnumerable
{
private Persons m_persons;
internal PersonsEnumerable(Persons persons)
{
m_persons = persons;
}
IEnumerator IEnumerable.GetEnumerator()
{
return new PersonsEnumerator(m_persons);
}
}
public IEnumerable InOrder
{
get { return new PersonsEnumerable(this); }
}
public IEnumerable Reverse
{
get
{
int length=this.m_Names.Length;
Persons persons= new Persons();
persons.m_Names = new string[length];
for (int i = 0; i < length; i++)
{
persons.m_Names[i] = m_Names[length-i-1];
}
return new PersonsEnumerable(persons);
}
}
}
实现代码:
public static void EnumObject()
{
Persons p = new Persons("001","002","003");
//正向输出
foreach (string s in p.InOrder)
{
Console.WriteLine(s);
}
//反序输出
foreach (string s in p.Reverse)
{
Console.WriteLine(s);
}
}