foreach简单迭代器

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace foreach循环简单迭代
{
    class Program
    {
        static void Main(string[] args)
        {
            Person p = new Person();
            foreach (var item in p)
            {
                Console.WriteLine(item);
            }
            Console.ReadKey();
        }
    }

    class Person
    {
        string[] friends = new string[] { "yajie", "liupeng", "liuxin", "laowu", "pengtao" };

        public IEnumerator GetEnumerator()
        {
            for(int i = 0; i < friends.Length; i++)
            {
                yield return friends[i];//使用yield在编译时会产生一个枚举器。
            }
        }
    }
}

你可能感兴趣的:(C#.NET,C#.NET)