将带有多个参数的函数作为参数传递

6
我有这段代码,它接受一个没有参数的函数,并返回其运行时间。
public static Stopwatch With_StopWatch(Action action)
{
    var stopwatch = Stopwatch.StartNew();
    action();
    stopwatch.Stop();
    return stopwatch;
}

我希望将其转换为接受带参数的非 void 函数。我听说过 Func<> 委托,但我不知道如何使用它。我需要类似于以下内容(非常伪代码):

   public T measureThis(ref Stopwatch sw, TheFunctionToMeasure(parameterA,parameterB))
   {
       sw.Start(); // start stopwatch
       T returnVal = TheFunctionToMeasure(A,B); // call the func with the parameters
       stopwatch.Stop(); // stop sw
       return returnVal; // return my func's return val
   }

所以我需要获取传递函数的返回值,并在最后获取秒表。 非常感谢您的帮助!

1个回答

10

您的原始代码仍然可以工作。当您有参数时,人们调用它的方式会发生变化:

With_Stopwatch(MethodWithoutParameter);
With_Stopwatch(() => MethodWithParameters(param1, param2));

您也可以使用第二种语法来带参数调用该方法:

With_Stopwatch(() => MethodWithoutParameter());
With_Stopwatch(() => MethodWithParameters(param1, param2));

更新: 如果你想要返回值,你可以将measureThis函数更改为使用Func<T>而不是一个Action:

public T measureThis<T>(Stopwatch sw, Func<T> funcToMeasure)
{
    sw.Start();
    T returnVal = funcToMeasure();
    sw.Stop();
    return returnVal;
}

Stopwatch sw = new Stopwatch();
int result = measureThis(sw, () => FunctionWithoutParameters());
Console.WriteLine("Elapsed: {0}, result: {1}", sw.Elapsed, result);
double result2 = meashreThis(sw, () => FuncWithParams(11, 22));
Console.WriteLine("Elapsed: {0}, result: {1}", sw.Elapsed, result);

谢谢,但是用这种技术,我能得到返回值吗? - Dominik Antal
如果您对返回值感兴趣,则应传递一个 Func<T>。我已经编辑了答案并提供了相关信息。 - carlosfigueira

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接