yield(C#2.0)
1.定义
yield return ??
yield break
向枚举数对象提供值||发出迭代结束信号
一、只能写在Iterator块当中
二、方法不能含有 out-ref
三、不能出现在匿名函数当中与catch||finally
2.基本使用
static IEnumerable<int> CreateSimpleIterator()
{
yield return 10;
for (int i = 0; i < 3; i++)
{
yield return i;
}
yield return 20;
}
//0 1 1 2 3 5 8 13
static IEnumerable<int> Fibonacci()
{
int current = 0;
int next = 1;
while (true)
{
yield return current;
int oldCurrent = current;
current = next;
next = next + oldCurrent;
}
}
//print:第一 print:第二 print:finally
static IEnumerable<string> Iterator()
{
try
{
Console.WriteLine("print:第一");
yield return "第一";
Console.WriteLine("print:第二");
yield return "第二";
}
finally
{
Console.WriteLine("print:finally");
}
}
//逐行读取
static IEnumerable<String> ReadLines(string path)
{
using (StreamReader sr = File.OpenText(path))
{
string? line;
while ((line = sr.ReadLine()) != null)
{
yield return line;
}
}
}
IEnumerable IEnumerator
1.自定义迭代器
internal class Person : IEnumerable
{
public String[] arrName = new String[10];
//虽然都用 => ,,,与lambda不一样。表达式主体(C#6.0)
public IEnumerator GetEnumerator() => new Persons(arrName);
private struct Persons : IEnumerator
{
private readonly String[]? m_Item;
private Int32 position = -1;
public Persons(String[] arr)
{
m_Item = arr ?? new String[0];
}
public object Current => m_Item![position];
public bool MoveNext() => ++position < m_Item!.Length ? true : false;
public void Reset() => position = -1;
}
}
IEnumerator iterator = new Person().GetEnumerator();
while (iterator.MoveNext())
{ //在对象集合中游走,而不暴露集合的实现
Console.WriteLine(iterator.Current);
}