C# 迭代器Iterator
1) Foreach 与迭代器的关系:foreach循环迭代语句可以用来迭代可枚举集合的所有元素
常见可枚举的类,Hashtable,集合,数组,字符串,List<>.....
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MyItrerator : MonoBehaviour {
public class Months : IEnumerable {
string[] months = { "1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月" };
public IEnumerator GetEnumerator() //迭代类:用 IEnumerator
{
for (int i = 0; i < months.Length; i++)
{
yield return months[i];
}
}
public IEnumerable Enumerable() //迭代类成员:用 IEnumerable
{
yield return this.GetEnumerator();
}
}
void Start () {
Months month = new Months();
foreach (string item in month) print(item);
}
}