让以下函数Measure
用于测量某些功能method
的执行时间
public static TimeSpan Measure(Action method)
{
var stopwatch = new Stopwatch();
stopwatch.Start();
method.Invoke();
stopwatch.Stop();
return stopwatch.Elapsed;
}
此方法由以下代码行启动
var ExecTime = ComplexityCounters.Measure(() => method(int a, int b));
如我们所见,它对Measure
的召回非常大,因此,让我们尝试通过以下函数将其简短化
public static TimeSpan ExecTime (Action method)
{
var ExecutionTime = Measure(() => method.Invoke());
return ExecutionTime;
}
但是
var ExecTime = ExecTime(method(int a, int b));
给出错误c#无法将其从“ void”转换为“ System.Action”。如何解决?还是有办法将这两个功能合而为一?
答案 0 :(得分:1)
此处为完整示例
public static TimeSpan Measure(Action method)
{
var stopwatch = new Stopwatch();
stopwatch.Start();
method.Invoke();
stopwatch.Stop();
return stopwatch.Elapsed;
}
public static TimeSpan ExecTime(Action method)
{
var ExecutionTime = Measure(() => method.Invoke());
return ExecutionTime;
}
private static void Main(string[] args)
{
var spentTime = ExecTime(() => Sum(1,2));
}
public static int Sum(int t1, int t2)
{
return t1 + t2;
}
实际上,您声明的变量ExecTime
与方法名ExecTime
相同