C#迭代器

1 篇文章 0 订阅
1 篇文章 0 订阅

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);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值