首页 > Windows开发 > 详细

yield return in C#

时间:2015-12-14 10:49:30      阅读:234      评论:0      收藏:0      [点我收藏+]

Yield has two great uses

  1. It helps to provide custom iteration with out creating temp collections.

  2. It helps to do stateful iteration

Iteration. It creates a state machine "under the covers" that remembers where you were on each additional cycle of the function and picks up from there.

 

e.g.

private static IEnumerable<string> GetIdList(DateTime startTime, DateTime endTime)
{
    var collectionList = new List<string>();

    for (var dateTime = new DateTime(startTime.Year, startTime.Month, 1); dateTime <= endTime; dateTime = dateTime.AddMonths(1))
    {
        collectionList.Add(dateTime.ToString("d"));
    }

    return collectionList;
}

  could be writen as:

private static IEnumerable<string> GetIdList(DateTime startTime, DateTime endTime)
{
    for (var dateTime = new DateTime(startTime.Year, startTime.Month, 1); dateTime <= endTime; dateTime = dateTime.AddMonths(1))
    {
        yield return collectionList.Add(dateTime.ToString("d"));
    }
}

  

 

  1. It helps to provide custom iteration with out creating temp collections.
  2. It helps to do stateful iteration.

  3. In order to explain the above two points more demonstratively, I have created a simple video and the link for same is here: http://www.youtube.com/watch?v=4fju3xcm21M

yield return in C#

原文:http://www.cnblogs.com/wushuaiyi/p/5044293.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!