如何使用方法调用作为参数

时间:2019-10-11 11:54:49

标签: c# .net lambda delegates

在C#中,如何通过将一个方法作为另一个方法的参数来传递方法,方法是将参数传递给被调用的方法,以便在内部调用该方法,例如,以测量其执行为目标?

代码是否可以接近以下伪代码?

var fs = require('fs');

 fs.readFile('run_results.json','utf8', function (err, data) {
     if (err) throw err;
     console.log('Data here =>', data);
 });

这里的主要问题似乎是如何传递和推导被调用者参数p1,p2,p3,p4,p5,p6。如何写得尽可能灵活和简单?

1 个答案:

答案 0 :(得分:3)

您可以在创建要计时的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);
        }
    }
}

此方法类似于“部分函数应用程序” as discussed in this article

注意:如果由于使用的是C#的较旧版本而无法使用元组,则必须声明如下计时方法:

public static T TimeFunction<T>(Func<T> func, out TimeSpan duration)
{
    var sw = Stopwatch.StartNew();
    var result = func();
    duration = sw.Elapsed;

    return result;
}

并相应地更改对其的调用。

相关问题