Why does an IEnumerator have to have at least one yield statement, even if it's unreachable?

后端 未结 2 1393
离开以前
离开以前 2021-01-21 04:44

Why does this code:

public IEnumerator Test()
{
}

Gives you an error:

Error CS0161 \'Test.GetEnumerator()\': not all cod

2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-21 05:28

    If there aren't any yield statements in the method block at all, then it's not an iterator block and the compiler has no idea that you want to perform the relevant transformations on it. It's going to treat it just like any other method where you return a value.

    The compiler team could have done what they did with async and added a new keyword to the signature of the method, which, if present, made the method an iterator block, allowed yield statements in the body, and would allow an empty body to be treated as yielding nothing, but they chose not to.

    If there is a yield statement in the method body somewhere there isn't actually any need for one to reliably be hit for the method to properly compile and run. In an iterator block hitting the end of the method means the sequence is over, even if no items have yet been yielded, which is an entirely sensible behavior. The method still has an IEnumerable or IEnumerator to return, it just has no values to yield.

提交回复
热议问题