通过匿名操作调用ForEach

时间:2018-05-05 05:11:39

标签: c#

编译此代码:

           var arr = new[] { 1, 3, 5, 7, 9, 11, 13, 15, 17, 19 };
           arr.ForEach(x =>
                    {
                          Console.WriteLine(x);
                    });

失败:

error CS7036: There is no argument given that corresponds to the required formal parameter 'action' of 'Array.ForEach<T>(T[], Action<T>)'

为什么?

1 个答案:

答案 0 :(得分:2)

ForEachArray类的静态方法。但是,它不是一种扩展方法。

该方法的文档说明了以下内容(强调我的):

  

指定数组的每个元素执行指定的操作。

需要两个参数:

  1. T[] - 在其元素上执行操作的一维零基数组。
  2. Action<T> - 要对数组的每个元素执行的操作。
  3. 你需要这样称呼它:

    Array.ForEach(arr, x =>
    {
        Console.WriteLine(x);
    });