简体   繁体   English

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

[英]Using array of Action() in a lambda expression

I want to do some performance measurement for a method that does some work with int arrays, so I wrote the following class: 我想为一些使用int数组的方法做一些性能测量,所以我编写了以下类:

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

But I can not call the Measure mehotd for the example below: 但我不能将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)
        });

I get the following errors: 我收到以下错误:

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'

Here is the method that works with arrays: 以下是适用于数组的方法:

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);
}

What I am doing wrong? 我做错了什么?

Measure expects its first argument to be an Action[] , not a lambda that returns an Action[] . Measure期望它的第一个参数是Action[] ,而不是返回Action[]的lambda。 And the actions array expects you to pass delegates, while you are in fact calling FillArray . 并且actions数组希望您传递委托,而实际上是在调用 FillArray

You probably want this: 你可能想要这个:

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

Cannot implicitly convert type 'void' to 'System.Action' 无法将类型'void'隐式转换为'System.Action'

This array initializer is expected to fill out the array with Action s returned by the FillArray method which is not the case. 期望这个数组初始值设定项使用FillArray方法返回的Action来填充数组,而不是这种情况。

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

Change the FillArray accordingly to return an Action instead of void 相应地更改FillArray以返回Action而不是void

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM