作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
假设我正在对一堆不同的函数进行基准测试,我只想调用一个函数来运行函数 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/
我是一名优秀的程序员,十分优秀!