2012-05-18 106 views
2

我有这段代码,它接受一个没有参数的函数,并返回它的运行时。传递一个具有多个参数的函数作为参数

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 
    } 

所以我必须得到通过FUNC的返回值,并获得最终的秒表。 任何帮助,非常感谢!

回答

7

您的原始代码仍然可以工作。人们如何将它称为是什么样的变化,当你有参数:

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

您也可以致电与第二语法参数的方法:

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

更新:如果你想返回值,你可以改变你measureThis功能采取Func<T>,而不是一个行动:

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); 
+0

谢谢你,但这种技术,我能得到日e返回值? –

+0

如果你对返回值感兴趣,那么你应该通过'Func '代替。我已经编辑了有关它的信息的答案。 – carlosfigueira

+0

非常感谢! –

相关问题