我可以创建一个接受泛型函数作为参数的函数吗?

Nat*_*man 2 c# generics function-pointers

假设我正在对一系列不同的函数进行基准测试,我只想调用一个函数来运行函数foo n次.

当所有函数具有相同的返回类型时,您就可以这样做

static void benchmark(Func<ReturnType> function, int iterations)
{
    Console.WriteLine("Running {0} {1} times.", function.Method.Name, iterations);
    Stopwatch stopwatch = new Stopwatch();
    stopwatch.Start();
    for (int i = 0; i < iterations; ++i)
    {
        function();
    }
    stopwatch.Stop();
    Console.WriteLine("Took {0} to run {1} {2} times.", stopwatch.Elapsed, function.Method.Name, iterations);
}
Run Code Online (Sandbox Code Playgroud)

但是,如果我正在测试的函数有不同的返回类型呢?我可以接受泛型类型的函数吗?我尝试使用,Func <T>但它不起作用.

Jon*_*eet 6

当然,你可以使它成为通用的:

static void Benchmark<T>(Func<T> function, int iterations)
Run Code Online (Sandbox Code Playgroud)

Action对于void方法,您可能还希望重载它以接受它.