我有这段代码,它接受一个没有参数的单一函数,并返回其运行时。public static Stopwatch With_StopWatch(Action action){ var stopwatch = Stopwatch.StartNew(); action(); stopwatch.Stop(); return stopwatch;}我想将其转换为带参数的非void函数。我听说过Func 委托(delegate),但是我不知道如何使用它。我需要这样的东西(非常伪): 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 }因此,我必须获取传递的仿函数的返回值,并最终获取秒表。任何帮助是极大的赞赏! 最佳答案 您的原始代码仍然可以使用。当您有参数时,人们将如何称呼它是什么: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);关于c# - 传递带有多个参数的函数作为参数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10645225/ 10-11 15:42