您的位置:首页 > 编程语言 > C#

C#迭代器的实现

2016-12-05 10:58 260 查看
using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

namespace iterator

{

abstract class ITerator//创建抽象迭代接口

{

public abstract object Fir();

public abstract object Sec();

public abstract bool Judge();

public abstract object GetCounts();

}

}

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

namespace iterator

{

abstract class Aggregate

{

public abstract ITerator ConcreteIterator();//设置存放的接口,及迭代器

}

}

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

namespace iterator

{

class ConcreteAggregate:Aggregate

{

private IList items = new List();//创建存放需要迭代的目标

public int count//设置属性,列表中的元素数量

{

get{ return items.Count; }

}

public object this[int index]//创建检索目录

{

get { return items[index];}

set { items.Insert(index,value);}

}

public override ITerator ConcreteIterator()//重写
{
return new ConcreteIterator(this);
}

}


}

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

namespace iterator

{

class ConcreteIterator:ITerator

{

private ConcreteAggregate aggregate;//关联存放类

private int CurrentCount = 0;//定义当前计数初始值

public ConcreteIterator(ConcreteAggregate aggregate)//传参

{

this.aggregate = aggregate;

}

public override object Fir()//获取列表中的第一个对象
{
return aggregate[0];
}

public override object Sec()//重写,这里实现迭代
{
object Now = null;
CurrentCount++;
if (CurrentCount <aggregate.count)
{
Now=aggregate[CurrentCount];
}
return Now;
}

public override bool Judge()//判断是否越界
{
return CurrentCount < aggregate.count ? true : false;
}

public override object GetCounts()//得到当前迭代得到的值
{
return  aggregate[CurrentCount];
}
}


}

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

namespace iterator

{

class Program

{

static void Main(string[] args)

{

ConcreteAggregate ca = new ConcreteAggregate();

ITerator it=new ConcreteIterator(ca);

ca[0] = “自行车”;

ca[1] = “轿车”;

ca[2] = “货车”;

ca[3] = “客车”;

ca[4] = “出租车”;

ca[5] = “人”;

it.Fir();

while (it.Judge())

{

Console.WriteLine(“{0}必须遵守交通规则!”, it.GetCounts());

it.Sec();

}

Console.ReadKey();

}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  迭代器 C#