调用方法作为方法参数但不执行? [英] Calling a method as a method parameter but not executing?

查看:109
本文介绍了调用方法作为方法参数但不执行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试实现一个方法,该方法将一个方法(事物的总体方案中的任何方法)作为参数。我希望此参数方法仅在调用它的方法中运行,如果传递给该方法的方法具有返回值,则它仍应能够返回其值。

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;
}

我尝试使用 Action 几乎可以满足我的使用方式

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

问题是 action()返回 void ,所以我无法按照自己的方式使用它。

Problem is action() returns void so I can't use it the way I would like to.

我看过 Func ,但我看不到如何通过 GetNextPage Performance 方法传入了c $ c>方法。

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.

推荐答案

您需要传递 Func< T> 性能

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;
}

我认为您还需要单独的措施方法用于不返回值的方法,接受 Action 像当前一样。

I think you'll also need your separate Measure method for methods that don't return values, accepting Action as it currently does.

您对 Performance 的调用变为:

return Performance(() => GetNextPage(eEvent, false));

eEvent false 成为闭包的一部分,因此获取并返回的只是 GetNextPage 的返回结果。

eEvent and false become part of the closure, so it's just the return result of GetNextPage that is acquired and returned.

这篇关于调用方法作为方法参数但不执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆