净2迭代器的巧妙用途巧妙、用途、迭代

2023-09-03 09:16:50 作者:且行且爱EXO

C#2和VB.Net 8引入了一个名为迭代器的新功能,它被设计为了更容易返回可枚举和枚举。

C# 2 and VB.Net 8 introduced a new feature called iterators, which were designed to make it easier to return enumerables and enumerators.

不过,迭代器实际上是有限的协程的形式,并且可以用来做什么都没有很多有用的东西做对象的集合。

However, iterators are actually a limited form of coroutines, and can be used to do many useful things that have nothing to do with collections of objects.

什么迭代器的非标准用途你在现实code见过?

What non-standard uses of iterators have you seen in real code?

推荐答案

我用他们写在ASP.NET中的系统创建一系列链接页面的交互。如果你想象一个用户的对话与网站的一系列请求和响应,你可以模拟一个交互的的IEnumerable 。从概念上讲,这样的;

I used them to write a system in ASP.NET for creating a series of linked page interactions. If you imagine a user's conversation with a website as a series of requests and responses, you can model an interaction as an IEnumerable. Conceptually, like this;

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.");
   } 
}

您可以存储在会话状态的迭代器,这样当用户返回到该网站,你只拉了出来迭代器,移动迭代器到下一个页面,它产生回渲染。复杂的网站交互是codeD在同一个地方。

You can store the iterator in session state, so that when the user returns to the site you just pull the iterator out, move the iterator onto the next page, and yield it back for rendering. Complex site interactions are coded in a single place.