c# 数组迭代器简介 基于unity2018.3.8f1(一)

简介

  迭代器模式是设计模式中的一种,能够获得序列中的元素,不关心其具体内容。这也是LINQ的核心模式。

具体实现

  先创建一个单体的数据类 Car 代码如下:

public class Car
{
    public string carName;
    public int carPrice;
    public Car(string carName, int carPrice)
    {
        this.carName = carName;
        this.carPrice = carPrice;
    }
}

  我们利用IEnumerable接口去封装一个Car数组 代码如下

public class CardList : IEnumerable
{
    Car[] carList;

    public CardList(Car[] carList)
    {
        this.carList = carList;
    }

    public int Count
    {
        get
        {
            return carList.Length;
        }
    }

    public Car this[int index]
    {
        get
        {
            return carList[index];
        }
    }

    public IEnumerator GetEnumerator()
    {
        throw new System.NotImplementedException();
    }
}

  接下来我们实现GetEnumerator函数里面的内容 新建CarIterator类,继承IEnumerator 并在MoveNext()函数中 和 Reset() 函数中进行修改 代码如下

public class CarIterator : IEnumerator
{
    private readonly CardList cardList;
    private int position = -1;

    public object Current
    {
        get
        {
            try
            {
                return cardList[position];
            }
            catch
            {
                throw new Exception();
            }
        }
    }

    public CarIterator(CardList cardList)
    {
        this.cardList = cardList;
    }

    public bool MoveNext()
    {
        position++;
        return position < cardList.Count;
    }

    public void Reset()
    {
        position = -1;
    }
}

  并把IEnumerable接口函数替换成

 public IEnumerator GetEnumerator()
    {
        return new CarIterator(this);
    }

  简单实现调用下

public class GameStart : MonoBehaviour
{
    private void Start()
    {
        Car[] cars = new Car[]
        {
            new Car("天斯",22),
            new Car("劳赖",33)
        };
        CardList cardList = new CardList(cars);
        foreach (Car item in cardList)
        {
            Debug.LogFormat("{0}:{1}", item.carName, item.carPrice);
        }
    }
}

调用结果 

 

posted @ 2019-06-18 13:21  Ely_Heng  阅读(419)  评论(0编辑  收藏  举报