代码之家  ›  专栏  ›  技术社区  ›  Tinku

c语言中的内部迭代器#

c#
  •  2
  • Tinku  · 技术社区  · 16 年前

    如何在c#中实现内部迭代器?

    3 回复  |  直到 16 年前
        1
  •  3
  •   Wim Coenen    16 年前

    我发现 this definition

    内部迭代器是 HigherOrderFunction 这需要一个 集合和函数并应用 收集

    假设这就是你想要的,下面是如何在C#中实现的:

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

    示例使用:

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

    here 就是一个例子

        3
  •  1
  •   Marc Gravell    16 年前

    foreach (或同等)为您(以最合适的方式为您提供数据)?就像 List<T>.ForEach Action<T> ,并依次应用于每个。

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

    我避免使用 foreach公司 foreach公司 尚未提供。

    然而,国际海事组织自C#(从2.0开始)以来 yield return 语法(迭代器块),更容易支持 IEnumerable<T> . 你当然可以加一个 ForEach 上的扩展方法 ;-p内部迭代器在.NET 1.1(C#1.2)中可能很有吸引力,其中(正确地)编写迭代器是 难以置信地