Interesting use of the C# yield keyword in Nerd Dinner tutorial

后端 未结 3 1237
不思量自难忘°
不思量自难忘° 2021-02-02 17:35

Working through a tutorial (Professional ASP.NET MVC - Nerd Dinner), I came across this snippet of code:

public IEnumerable GetRuleViolation         


        
3条回答
  •  不要未来只要你来
    2021-02-02 17:38

    Short version:

    1: The yield is the magic "Stop and come back later" keyword, so the if statements in front of the "active" one have been evaluated.

    2: yield break explicitly ends the enumeration (think "break" in a switch case)

    3: Every time. You can cache the result, of course, by turning it into a List for example and iterating over that afterwards.

提交回复
热议问题