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

后端 未结 3 1183
不思量自难忘°
不思量自难忘° 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:55

    1) Take this simpler example:

    public void Enumerate()
    {
        foreach (var item in EnumerateItems())
        {
            Console.WriteLine(item);
        }
    }
    
    public IEnumerable EnumerateItems()
    {
        yield return "item1";
        yield return "item2";
        yield break;
    }
    

    Each time you call MoveNext() from the IEnumerator the code returns from the yield point and moves to the next executable line of code.

    2) yield break; will tell the IEnumerator that there is nothing more to enumerate.

    3) once per enumeration.

    Using yield break;

    public IEnumerable EnumerateUntilEmpty()
    {
        foreach (var name in nameList)
        {
            if (String.IsNullOrEmpty(name)) yield break;
            yield return name;
        }     
    }
    

提交回复
热议问题