[英]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.