代码改变世界

C#中yield return的思想

2011-08-25 12:03  zhoujie  阅读(411)  评论(0编辑  收藏  举报

C#中为什么引入yield return? 我想是为了使for each更容易使用.yield return的思想也就是foreach的思想:为了使遍历的语义更加自然,接近人类思想。

C#编译器在背后为我们作了大量的工作,以便我们代码的可读性更好!请看下面代码:

 

using System;
using System.Text;
using System.Collections;

namespace yieldReturn
{
    
public class List
    {
        
//using System.Collections;
        public static IEnumerable Power(int number, int exponent)
        {
            
int counter = 0;
            
int result = 1;
            
while (counter++ < exponent)
            {
                result 
= result * number;
                
yield return result;
            }
        }

        
static void Main()
        {
             
//Display powers of 2 up to the exponent 8:
            foreach (int i in Power(28))
            {
                Console.Write(
"{0} ", i);
            }
            Console.Read();
        }
    }

}

有了yield return,可以方便地为我们提供foreach下一个要访问的元素!