gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 19:41:34 25 4
gpt4 key购买 nike

假设我正在对一堆不同的函数进行基准测试,我只想调用一个函数来运行函数 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);
}

但是如果我正在测试的函数有不同的返回类型怎么办?我可以接受具有通用类型的函数吗?我尝试使用 Func <T>但它不起作用。

最佳答案

你当然可以让它变得通用:

static void Benchmark<T>(Func<T> function, int iterations)

您可能还想重载它以接受 Action,用于 void 方法。

关于c# - 我可以创建一个接受泛型函数作为参数的函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19436213/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com