在C#中,如何通过将一个方法作为另一个方法的参数来传递方法,方法是将参数传递给被调用的方法,以便在内部调用该方法,例如,以测量其执行为目标?
该代码可以接近以下伪代码吗?
public TR MeasureExecutionTime<T1, T2, T3, T4, T5, T6, TR>(this Func<T1, T2, T3, T4, T5, T6, TR> func, out long executionTime)
{
Stopwatch stopwatch = Stopwatch.StartNew();
TR tr = func();
stopwatch.Stop();
executionTime = stopwatch.ElapsedMilliseconds;
return tr;
}
...
var result = MeasureExecutionTime(() => obj.Process(p1, p2, p3, p4, p5, p6), out long executionTime);
这里的主要问题似乎是如何传递和推导被调用者参数p1,p2,p3,p4,p5,p6。如何写得尽可能灵活和简单?
您可以在创建要计时的lambda时应用参数,而不是在进行计时的方法中应用参数。
因此,您可以像这样实现计时功能(使用元组返回两个值):
public static (TimeSpan duration, T result) TimeFunction<T>(Func<T> func)
{
var sw = Stopwatch.StartNew();
var result = func();
return (sw.Elapsed, result);
}
您可以使用它来计时具有多个参数的函数,如下所示:
using System;
using System.Diagnostics;
using System.Threading;
namespace ConsoleApp1
{
class Program
{
public static void Main()
{
// Note how we apply the parameters here, even though the
// function is actually called inside TimeFunction().
var result = TimeFunction(() => functionToTime(1, 2.0, "3"));
Console.WriteLine("Result = " + result.value);
Console.WriteLine("Duration = " + result.duration);
}
static string functionToTime(int intVal, double doubleVal, string stringVal)
{
Thread.Sleep(250);
return $"intVal = {intVal}, doubleVal = {doubleVal}, stringVal = {stringVal}";
}
public static (TimeSpan duration, T value) TimeFunction<T>(Func<T> func)
{
var sw = Stopwatch.StartNew();
var result = func();
return (sw.Elapsed, result);
}
}
}
这种方法类似于本文中讨论的“部分函数应用程序” 。
注意:如果由于使用的是C#的较旧版本而无法使用元组,则必须声明计时方法,如下所示:
public static T TimeFunction<T>(Func<T> func, out TimeSpan duration)
{
var sw = Stopwatch.StartNew();
var result = func();
duration = sw.Elapsed;
return result;
}
并相应地更改对其的调用。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句