yield是C#爲了簡化遍歷操做實現的語法糖,咱們知道若是要要某個類型支持遍歷就必需要實現系統接口IEnumerable,這個接口後續實現比較繁瑣要寫一大堆代碼才能支持真正的遍歷功能。舉例說明函數
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
namespace
{
class Program
{
static void Main(string[] args)
{
HelloCollection helloCollection = new HelloCollection();
foreach (string s in helloCollection)
{
Console.WriteLine(s);
}
Console.ReadKey();
}
}
//
public class HelloCollection : IEnumerable
//
{
//
public IEnumerator GetEnumerator()
//
{
//
yield return "Hello";
//
yield return "World";
//
}
//}
public class HelloCollection : IEnumerable
{
public IEnumerator GetEnumerator()
{
Enumerator enumerator = new Enumerator(0);
return enumerator;
}
public class Enumerator : IEnumerator, IDisposable
{
private int state;
private object current;
public Enumerator(int state)
{
this.state = state;
}
public bool MoveNext()
{
switch (state)
{
case 0:
current = "Hello";
state = 1;
return true;
case 1:
current = "World";
state = 2;
return true;
case 2:
break;
}
return false;
}
public void Reset()
{
throw new NotSupportedException();
}
public object Current
{
get { return current; }
}
public void Dispose()
{
}
}
}
}
class A : IEnumerable
{
private int[] array = new int[10];
public IEnumerator GetEnumerator()
{
for (int i = 0; i < 10; i++)
{
yield return array[i];
}
}
}
public IEnumerator GetEnumerator()
{
for (int i = 0; i < 10; i++)
{
if (i < 8)
{
yield return array[i];
}
else
{
yield break;
}
}
}
這樣,則只會返回前8個數據.blog