编译此代码:
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>)'
为什么?
答案 0 :(得分:2)
ForEach
是Array
类的静态方法。但是,它不是一种扩展方法。
该方法的文档说明了以下内容(强调我的):
对指定数组的每个元素执行指定的操作。
需要两个参数:
T[]
- 在其元素上执行操作的一维零基数组。Action<T>
- 要对数组的每个元素执行的操作。你需要这样称呼它:
Array.ForEach(arr, x =>
{
Console.WriteLine(x);
});