开发者

Internal Iterator in c#

开发者 https://www.devze.com 2022-12-14 05:32 出处:网络
How can I implement internal iterator in 开发者_C百科c# ?I found this definition of \"internal iterator\" on the c2 wiki:

How can I implement internal iterator in 开发者_C百科c# ?


I found this definition of "internal iterator" on the c2 wiki:

An Internal Iterator is a HigherOrderFunction that takes a collection and a function and applies the function to every element of the collection

Assuming that's what you want, here's how to do it in C#:

static void ForEach<T>(IEnumerable<T> enumerable, Action<T> action)
{
   foreach (T item in enumerable)
   {
      action(item);
   }
}

Example use:

Action<int> printer = x => Console.WriteLine(x);
var numbers = new int[] { 1, 2, 3};
ForEach(numbers, printer);


here is an example


Do you mean something that does the foreach (or equivalent) for you (in the most appropriate way for the data)? Like List<T>.ForEach? This is where delegates come to the fore; just pass an Action<T>, and apply to each in turn.

public void SomeMethod(Action<MyDataType> action) {
    {for each item} // pseudo#
        action(item);
    {end}
}

I've avoided using foreach in the above deliberately, as this most commonly applies to scenarios where foreach isn't already provided.

However; IMO, since C# (from 2.0 onwards) has yield return syntax (iterator blocks), it is easier just to support IEnumerable<T>. You could of course add a ForEach extension method on IEnumerable<T> ;-p Internal iterators may have been attractive in .NET 1.1 (C# 1.2) where (correctly) writing an iterator was incredibly painful.

0

精彩评论

暂无评论...
验证码 换一张
取 消