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

后端 未结 5 1636
孤街浪徒
孤街浪徒 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:33

    No you can't do that - an iterator block (something with a yield) cannot use the regular (non-yield) return. Instead, you need to use 2 methods:

    public IEnumerable GetIntegers3()
    {
      if ( someCondition )
      {
        return new[] {4, 5, 6}; // compiler error
      }
      else
      {
        return GetIntegers3Deferred();
      }
    }
    private IEnumerable GetIntegers3Deferred()
    {
        yield return 1;
        yield return 2;
        yield return 3;
    }
    

    or since in this specific case the code for both already exists in the other 2 methods:

    public IEnumerable GetIntegers3()
    {
      return ( someCondition ) ? GetIntegers1() : GetIntegers2();
    }
    

提交回复
热议问题