Calling a method as a method parameter but not executing?

孤街醉人 提交于 2020-05-09 10:28:10

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!