2013-10-17 101 views
2

假設我正在對一堆不同的函數進行基準測試,並且我只想調用一個函數來運行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>,但它不起作用。

+0

解釋不起作用 –

+0

你可以發佈你的代碼是什麼樣的你的嘗試? – Jared

+0

如果你想在c#中使用示例,請查看LINQ。傳遞這樣的通用函數作爲參數是其基石之一...... – 2013-10-17 20:26:56

回答

6

你可以把它通用的,肯定:

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

您可能還需要重載它接受Action,爲void方法。

+0

你是最棒的Jon Skeet。這確實是我正在尋找的。完美的作品。 – NathanTempelman

+1

如果您可以使用Func 進行操作,我覺得語言會更好。 – Random832

+1

@ Random832:許多事情會更簡單。我們可以有'Task '而不是'Task',... –

1
static void benchmarkFoo<T>(Func<T> foo, int n) 
         ^ ^

請注意上述地方的通用參數。足夠了。

1
static void BenchmarkFoo<T>(Func<T> foo, int n) where T :new() <-- condition on T 

根據你想要做的那個返回值,你可能需要在你的泛型上添加條件。

相關問題