C# 迭代器Iterator

来源:互联网 发布:php 不识别utf8 编辑:程序博客网 时间:2024/06/15 11:12

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 itemin month)  print(item); 

}

 

}

















原创粉丝点击