聪明地使用.Net 2迭代器

SLa*_*aks 14 .net c# vb.net iterator

C#2和VB.Net 8引入了一个名为迭代器的新功能,旨在使返回枚举数和枚举数变得更容易.

但是,迭代器实际上是一种有限形式的协同程序,可以用来做许多与对象集合无关的有用的东西.

您在实际代码中看到了什么非标准的迭代器用法?

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)

您可以将迭代器存储在会话状态中,这样当用户返回到站点时,您只需将迭代器拉出,将迭代器移动到下一页,然后将其返回以进行渲染.复杂的站点交互在一个地方编码.

  • @Marc Gravell - 你必须承认这很酷,即使它不适用于某些硬件配置. (4认同)

SLa*_*aks 8

开始时:

  • Jeffrey Richter使用迭代器编写了一个名为AsyncEnumerator的强大线程系统.它在MSDN杂志,部分描述一个2.
  • 迭代器也可用于等待方法中的UI交互,而不会阻塞UI线程,如我在此处所述.
  • 类似地,我使用迭代器创建一个基于IE的Web scraper,使用抓取方法返回WebActions的IEnumerators,它们在准备好时回调到枚举器中.(通常,当文档完成加载时).
    如果人们有兴趣,我可以在这里发布.