在 lambda 表达式中使用 Action() 数组

本文关键字:Action 数组 lambda 表达式 | 更新日期: 2023-09-27 18:36:45

我想对一个处理 int 数组的方法进行一些性能测量,所以我写了以下类:

public class TimeKeeper
{
    public TimeSpan Measure(Action[] actions)
    {
        var watch = new Stopwatch();
        watch.Start();
        foreach (var action in actions)
        {
            action();
        }
        return watch.Elapsed;
    }
}

但是对于以下示例,我不能将Measure称为mehotd:

var elpased = new TimeKeeper();
elpased.Measure(
    () =>
    new Action[]
        {
            FillArray(ref a, "a", 10000),
            FillArray(ref a, "a", 10000),
            FillArray(ref a, "a", 10000)
        });

我收到以下错误:

Cannot convert lambda expression to type 'System.Action[]' because it is not a delegate type
Cannot implicitly convert type 'void' to 'System.Action'
Cannot implicitly convert type 'void' to 'System.Action'
Cannot implicitly convert type 'void' to 'System.Action'

以下是处理数组的方法:

private void FillArray(ref int[] array, string name, int count)
{
    array = new int[count];
    for (int i = 0; i < array.Length; i++)
    {
        array[i] = i;
    }
    Console.WriteLine("Array {0} is now filled up with {1} values", name, count);
}

我做错了什么?

在 lambda 表达式中使用 Action() 数组

>Measure期望它的第一个参数是一个Action[],而不是返回Action[]的lambda。动作数组希望您传递委托,而您实际上是在调用FillArray

你可能想要这个:

elpased.Measure
(
    new Action[]
    {
        () => FillArray(ref a, "a", 10000),
        () => FillArray(ref a, "a", 10000),
        () => FillArray(ref a, "a", 10000)
    }
);

无法将类型"void"隐式转换为"System.Action"

此数组初始值设定项应使用 FillArray 方法返回的 Action s 填充数组,但事实并非如此。

new Action[]
        {
            FillArray(ref a, "a", 10000),
            FillArray(ref a, "a", 10000),
            FillArray(ref a, "a", 10000)
        });

相应地更改FillArray以返回Action而不是void