不常用,一般的数组容器都会给定自己的迭代器,使用现成的就好了,一般不需要自己实现。
//抽象迭代器
public interface Iterator {
object First();
object Next();
bool HasNext();
object Current();
}//抽象容器
public interface Comtainer {
void Add(object o);
void Remove(object o);
Iterator CreateInterator();
}//具体迭代器
using System.Collections.Generic;
public class AIterator : Iterator
{
private List<object> list;
private int currentIndex = 0;
public AIterator(List<object> l)
{
list = l;
}
public object Current()
{
return list[currentIndex];
}
public object First()
{
if (list.Count > 0) {
return list[0];
}
return null;
}
public bool HasNext()
{
if (currentIndex >= list.Count) {
return false;
}
return true;
}
public object Next()
{
object current = list[currentIndex];
currentIndex++;
return current;
}
}//具体容器
using System.Collections.Generic;
public class AContainer : Comtainer
{
private List<object> list = new List<object>();
public void Add(object o)
{
list.Add(o);
}
public Iterator CreateInterator()
{
return new AIterator(list);
}
public void Remove(object o)
{
if (list.Contains(o)){
list.Remove(o);
}
}
}//测试使用
using UnityEngine;
public class tsetInterator : MonoBehaviour {
void Start () {
Comtainer aContainer = new AContainer();
aContainer.Add(10);
aContainer.Add(30);
aContainer.Add(80);
Iterator i = aContainer.CreateInterator();
while (i.HasNext()) {
Debug.Log(i.Next());
}
}
}就是为容器创建一个接口来创建迭代器,通过迭代器有访问遍历容器的数据的能力,记录当前位置等。