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

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

    Theoretically I think there is no reason why return and yield return can not be mixed: It would be an easy matter for the compiler to first syntactically transform any return (blabla()); sentence into:

    var myEnumerable = blabla();
    foreach (var m in myEnumerable) 
        yield return m; 
    yield break; 
    

    and then continue (to transform the whole method into ... whatever they transform it now; an inner anonymous IEnumerator class?!)

    So why did they not choose to implement it, here are two guesses:

    • they might have decided it would be confusing to the users to have both return and yield return at once,

    • Returning the whole enumerable is faster and cheaper but also eager; building via yield return is a little more expensive (especially if called recursively, see Eric Lippert's warning for traversal in binary trees with yield return statements here: https://stackoverflow.com/a/3970171/671084 for example) but lazy. So a user usually would not want to mix these: If you don't need laziness (i.e. you know the whole sequence) don't suffer the efficiency penalty, just use a normal method. They might have wanted to force the user to think along these lines.

    On the other hand, it does seem that there are situations where the user could benefit from some syntactic extensions; you might want to read this question and answers as an example (not the same question but one probably with a similar motive): Yield Return Many?

提交回复
热议问题