I have seen this syntax in MSDN: yield break
, but I don't know what it does. Does anyone know?
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Generic Generics in Managed C++
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
The yield keyword is used together with the return keyword to provide a value to the enumerator object. yield return specifies the value, or values, returned. When the yield return statement is reached, the current location is stored. Execution is restarted from this location the next time the iterator is called.
To explain the meaning using an example:
Values returned when this is iterated are: 0, 2, 5.
It’s important to note that counter variable in this example is a local variable. After the second iteration which returns the value of 2, third iteration starts from where it left before, while preserving the previous value of local variable named counter which was 2.
It specifies that an iterator has come to an end. You can think of
yield break
as areturn
statement which does not return a value.For example, if you define a function as an iterator, the body of the function may look like this:
Note that after the loop has completed all its cycles, the last line gets executed and you will see the message in your console app.
Or like this with
yield break
:In this case the last statement is never executed because we left the function early.
Tells the iterator that it's reached the end.
As an example:
Ends an iterator block (e.g. says there are no more elements in the IEnumerable).
The whole subject of iterator blocks is covered well in this free sample chapter from Jon Skeet's book C# in Depth.
The
yield break
statement causes the enumeration to stop. In effect,yield break
completes the enumeration without returning any additional items.Consider that there are actually two ways that an iterator method could stop iterating. In one case, the logic of the method could naturally exit the method after returning all the items. Here is an example:
In the above example, the iterator method will naturally stop executing once
maxCount
primes have been found.The
yield break
statement is another way for the iterator to cease enumerating. It is a way to break out of the enumeration early. Here is the same method as above. This time, the method has a limit on the amount of time that the method can execute.Notice the call to
yield break
. In effect, it is exiting the enumeration early.Notice too that the
yield break
works differently than just a plainbreak
. In the above example,yield break
exits the method without making the call toDebug.WriteLine(..)
.