【原】yield的最基本用法

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

namespace Itcast.Mall.ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] strs = new string[] { "1", "2", "3" };
            IEnumerable<int> ints = GetInts(strs);
            foreach (var item in ints)
            {
                //测试,当item的值大于1后,下面GetInts里的foreach只会执行到这个对应的值,后面的就冻结,不执行了,节约资源;
                if (item > 1)
                {
                    break;
                }
                Console.WriteLine(item);
            }
            Console.ReadKey();
        }
        static IEnumerable<int> GetInts(string[] strs)
        {
            foreach (var item in strs)
            {
                Console.WriteLine(item.GetType());
                yield return Convert.ToInt32(item);
            }
        }
    }
}
原文地址:https://www.cnblogs.com/gebenhagen/p/4457728.html