1.迭代类的封装
namespace Data
{
/*迭代器模式:仿照IEnumerator接口,实现一个简单的迭代器。*/
//迭代器接口
public interface IIterators
{
int currentIndexx { get; set; }
object GetCurrentItem();
object GetFirst();
void Next();
bool IsLast();
}
//具体实现
public class Iterators : IIterators
{
/// <summary>
/// 具体聚集对象
/// </summary>
private GatheredEx gatheredEx;
private int currentIndex;
/// <summary>
/// 接口中的属性
/// </summary>
int IIterators.currentIndexx
{
get
{
return currentIndex;
}
set
{
currentIndex = value;
}
}
/// <summary>
/// 在构造函数中实例化未来要遍历集合中的元素
/// </summary>
/// <param name="gatheredExObj"></param>
public Iterators(GatheredEx gatheredExObj)
{
gatheredEx = gatheredExObj;
}
#region IIterators 成员
/// <summary>
/// 得到当前对象
/// </summary>
/// <returns></returns>
public object GetCurrentItem()
{
return gatheredEx[currentIndex];
}
/// <summary>
/// 得到第一个对象
/// </summary>
/// <returns></returns>
public object GetFirst()
{
return gatheredEx[0];
}
/// <summary>
/// 修改索引值,以访问下一个对象
/// </summary>
/// <returns></returns>
public void Next()
{
currentIndex++;
}
/// <summary>
/// 是否为最后一个元素
/// </summary>
/// <returns></returns>
public bool IsLast()
{
return currentIndex < gatheredEx.Count;
}
#endregion
}
//聚集对象,用来表示要遍历的数组或集合
public abstract class Gathered
{
public abstract IIterators CreateIIterators();
}
//具体聚集类
public class GatheredEx : Gathered
{
//存放要遍历的对象
public IList<object> list = new List<object>();
public override IIterators CreateIIterators()
{
return new Iterators(this);
}
//返回集合中元素个数
public int Count { get { return list.Count; } }
/// <summary>
/// 定义索引器,允许对象可以按照数组的方式进行访问
/// this 关键字用于定义索引器
/// get 访问器返回值。set 访问器分配值
/// value 关键字用于定义由 set 索引器分配的值
/// 索引器的索引值并不一定非要整形,可根据自己的需求定义索引类型
/// 索引器可以有多个形参,例如当访问二维数组时(MSDN)
/// </summary>
/// <param name="index"></param>
/// <returns></returns>
public object this[int index]
{
get { return list[index]; }
set { list.Insert(index, value); }
}
}
}
2.调用
static void Main(string[] args)
{
/* g[0] = "A"; 是object类型,所以,通过数组方式访问该对象可以
* 为其赋任何类型的值*/
GatheredEx g = new GatheredEx();
g[0] = "A";
g[1] = "B";
g[2] = "C";
g[3] = "D";
g[4] = "E";
//把以上对象存入迭代器
IIterators it = new Iterators(g);
Console.WriteLine("获取第一个值:{0}",it.GetFirst());
while (it.IsLast())
{
Console.WriteLine("{0}为:{1}",it.currentIndexx,it.GetCurrentItem());
it.Next();
}
Console.ReadKey();
}