簡體   English   中英

在lambda表達式中使用Action()數組

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

我想為一些使用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);
}

我做錯了什么?

Measure期望它的第一個參數是Action[] ,而不是返回Action[]的lambda。 並且actions數組希望您傳遞委托,而實際上是在調用 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來填充數組,而不是這種情況。

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM