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

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

    return is eager. It returns the entire resultset at once. yield return builds an enumerator. Behind the scenes the C# compiler emits the necessary class for the enumerator when you use yield return. The compiler doesn't look for runtime conditions such as if ( someCondition ) when determining whether it should emit the code for an enumerable or have a method that returns a simple array. It detects that in your method you are using both which is not possible as he cannot emit the code for an enumerator and at the same time have the method return a normal array and all this for the same method.

提交回复
热议问题