Ste*_*per 11
我用它们在ASP.NET中编写一个系统来创建一系列链接页面交互.如果您将用户与网站的对话想象为一系列请求和响应,则可以将交互建模为IEnumerable.从概念上讲,就像这样;
IEnumerable<PageResponse> SignupProcess(FormValues form)
{
// signup starts with a welcome page, asking
// the user to accept the license.
yield return new WelcomePageResponse();
// if they don't accept the terms, direct
// them to a 'thanks anyway' screen
if (!form["userAcceptsTerms"])
{
yield return new ThanksForYourTimePageResponse();
yield break;
}
// On the second page, we gather their email;
yield new EmailCapturePage("");
while(!IsValid(form["address"]))
{
// loop until we get a valid address.
yield return new EmailCapturePage("The email address is incorrect. Please fix.");
}
}
Run Code Online (Sandbox Code Playgroud)
您可以将迭代器存储在会话状态中,这样当用户返回到站点时,您只需将迭代器拉出,将迭代器移动到下一页,然后将其返回以进行渲染.复杂的站点交互在一个地方编码.
开始时:
WebActions的IEnumerators,它们在准备好时回调到枚举器中.(通常,当文档完成加载时).