4

我想对使用 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);
}

我做错了什么?

4

2 回答 2

10

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

你可能想要这个:

elpased.Measure
(
    new Action[]
    {
        () => FillArray(ref a, "a", 10000),
        () => FillArray(ref a, "a", 10000),
        () => FillArray(ref a, "a", 10000)
    }
);
于 2012-06-09T22:23:12.070 回答
0

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

Action这个数组初始化器应该用方法返回的 s来填充数组,FillArray但事实并非如此。

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

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

于 2012-06-09T22:36:24.307 回答