传递具有多个参数的函数作为参数

Dom*_*tal 3 c# parameters stopwatch func measure

我有这段代码,它接受一个没有参数的函数,并返回它的运行时.

public static Stopwatch With_StopWatch(Action action)
{
    var stopwatch = Stopwatch.StartNew();
    action();
    stopwatch.Stop();
    return stopwatch;
}
Run Code Online (Sandbox Code Playgroud)

我想将其转换为带参数的非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
   }
Run Code Online (Sandbox Code Playgroud)

所以我必须得到传递的func的返回值,并最终获得秒表. 任何帮助是极大的赞赏!

car*_*ira 8

您的原始代码仍然有效.当你有参数时,人们如何调用它会发生什么变化:

With_Stopwatch(MethodWithoutParameter);
With_Stopwatch(() => MethodWithParameters(param1, param2));
Run Code Online (Sandbox Code Playgroud)

你也可以使用第二种语法调用参数方法:

With_Stopwatch(() => MethodWithoutParameter());
With_Stopwatch(() => MethodWithParameters(param1, param2));
Run Code Online (Sandbox Code Playgroud)

更新:如果你想要返回值,你可以改变你的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);
Run Code Online (Sandbox Code Playgroud)