C# 将方法作为方法参数调用但不执行?
嗨,我正在尝试实现一个方法,该方法将一个方法(事物大方案中的任何方法)作为参数。我希望此参数方法仅在调用它的方法中运行,如果传入此方法的方法具有返回值,则它仍应能够返回其值 我想测量传入的方法的性能C# 将方法作为方法参数调用但不执行?,c#,.net,methods,delegates,func,C#,.net,Methods,Delegates,Func,嗨,我正在尝试实现一个方法,该方法将一个方法(事物大方案中的任何方法)作为参数。我希望此参数方法仅在调用它的方法中运行,如果传入此方法的方法具有返回值,则它仍应能够返回其值 我想测量传入的方法的性能 return Performance(GetNextPage(eEvent, false)); public static T Performance<T>(T method) { T toReturn; Stopwatch sw = Stopwatch.StartNe
return Performance(GetNextPage(eEvent, false));
public static T Performance<T>(T method)
{
T toReturn;
Stopwatch sw = Stopwatch.StartNew();
toReturn = method;
sw.Stop();
Debug.WriteLine(sw.Elapsed.ToString());
return toReturn;
}
问题是action()
返回void
,所以我不能以我想要的方式使用它
我已经查看了
Func
,但是我不知道如何让它通过传入的GetNextPage
方法运行我的Performance
方法。您需要将Func
传递到Performance
:
return Performance(GetNextPage(eEvent, false));
public static T Performance<T>(T method)
{
T toReturn;
Stopwatch sw = Stopwatch.StartNew();
toReturn = method;
sw.Stop();
Debug.WriteLine(sw.Elapsed.ToString());
return toReturn;
}
public static T Performance<T>(Func<T> func)
{
T toReturn;
Stopwatch sw = Stopwatch.StartNew();
toReturn = func();
sw.Stop();
Debug.WriteLine(sw.Elapsed.ToString());
return toReturn;
}
eEvent
和false
成为闭包的一部分,因此获取并返回的只是GetNextPage
的返回结果
return Performance(() => GetNextPage(eEvent, false));