将函数转换为变量

时间:2019-04-04 18:04:01

标签: c# .net

让以下函数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”。如何解决?还是有办法将这两个功能合而为一?

1 个答案:

答案 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相同