问题
Hi I am trying to implement a method that will take a method (any method in the grand scheme of things) as a parameter. I want this parameter method to run when in the method that called it only, If the method that passes into this method has a return value then it should still be able to return its value.
I want to measure the performance of the methods that are passed in.
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;
}
I have tried using Action
which does work almost how I want to use it
public static TimeSpan Measure(Action action)
{
Stopwatch sw = Stopwatch.StartNew();
action();
sw.Stop();
return sw.Elapsed;
}
var dur = Measure(() => GetNextPage(eEvent, false));
Problem is action()
returns void
so I can't use it the way I would like to.
I have looked at Func
but I don't see how I can get it to run my Performance
method with the GetNextPage
method passed in.
回答1:
You need to pass Func<T>
to Performance
:
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;
}
I think you'll also need your separate Measure
method for methods that don't return values, accepting Action
as it currently does.
Your call to Performance
becomes:
return Performance(() => GetNextPage(eEvent, false));
eEvent
and false
become part of the closure, so it's just the return result of GetNextPage
that is acquired and returned.
来源:https://stackoverflow.com/questions/25403087/calling-a-method-as-a-method-parameter-but-not-executing