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(2, 8))
{
Console.Write("{0} ", i);
}
Console.Read();
}
}
}
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(2, 8))
{
Console.Write("{0} ", i);
}
Console.Read();
}
}
}
有了yield return,可以方便地为我们提供foreach下一个要访问的元素!