Why can't “return” and “yield return” be used in the same method?

后端 未结 5 1622
孤街浪徒
孤街浪徒 2021-02-05 04:35

Why can\'t we use both return and yield return in the same method?

For example, we can have GetIntegers1 and GetIntegers2 below, but not GetIntegers3.

pu         


        
5条回答
  •  一整个雨季
    2021-02-05 05:18

    The compiler re-writes any methods with a yield statement (return or break). It currently cannot handle methods that may or may not yield.

    I'd recommend having a read of chapter 6 of Jon Skeet's C# in Depth, of which chapter 6 is available for free - it covers iterator blocks quite nicely.

    I see no reason why this would not be possible in future versions of the c# compiler however. Other .Net languages do support something similar in the form of a 'yield from' operator (See F# yield!). If such an operator existed in c# it would allow you to write your code in the form:

    public IEnumerable GetIntegers()
    {
      if ( someCondition )
      {
        yield! return new[] {4, 5, 6};
      }
      else
      {
        yield return 1;
        yield return 2;
        yield return 3;
      }
    }
    

提交回复
热议问题