問題描述
我想以易于理解的形式了解有關 yield
語句的所有信息.
I want to know everything about the yield
statement, in an easy to understand form.
我已經閱讀了 yield
語句及其在實現迭代器模式時的易用性.但是,大部分都非常干燥.我想深入了解一下微軟是如何處理收益率的.
I have read about the yield
statement and its ease when implementing the iterator pattern. However, most of it is very dry. I would like to get under the covers and see how Microsoft handles return yield.
另外,你什么時候使用yield break?
Also, when do you use yield break?
推薦答案
yield
通過在內部構建狀態機來工作.它會在例程退出時存儲該例程的當前狀態,并在下次從該狀態恢復時存儲.
yield
works by building a state machine internally. It stores the current state of the routine when it exits and resumes from that state next time.
您可以使用 Reflector 查看編譯器是如何實現的.
You can use Reflector to see how it's implemented by the compiler.
yield break
當你想停止返回結果時使用.如果您沒有 yield break
,編譯器會在函數末尾假定一個(就像普通函數中的 return;
語句一樣)
yield break
is used when you want to stop returning results. If you don't have a yield break
, the compiler would assume one at the end of the function (just like a return;
statement in a normal function)
這篇關于yield 語句實現的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!