What are real life applications of yield?

前端 未结 7 1850
梦谈多话
梦谈多话 2020-12-15 23:12

I know what yield does, and I\'ve seen a few examples, but I can\'t think of real life applications, have you used it to solve some specific problem?

(I

7条回答
  •  甜味超标
    2020-12-15 23:38

    actually I use it in a non traditional way on my site IdeaPipe

    public override IEnumerator GetEnumerator()
    {
        // goes through the collection and only returns the ones that are visible for the current user
        // this is done at this level instead of the display level so that ideas do not bleed through
        // on services
        foreach (T idea in InternalCollection)
            if (idea.IsViewingAuthorized)
                yield return idea;
    }
    

    so basically it checks if viewing the idea is currently authorized and if it is it returns the idea. If it isn't, it is just skipped. This allows me to cache the Ideas but still display the ideas to the users that are authorized. Else I would have to re pull them each time based on permissions, when they are only re-ranked every 1 hour.

提交回复
热议问题