How to write a C # method that will take an introduced dependency of an unknown type?

Background

I have several utility methods that I would like to add to the solution I'm working on, and using dependency injection will open up many more potential uses for these methods.

I am using C #, .NET 4

Here is an example of what I'm trying to accomplish (this is just an example):

public static void PerformanceTest(Func<???> func, int iterations) { var stopWatch = new Stopwatch(); stopWatch.Start(); for (int i = 0; i < iterations; i++) { var x = func(); } stopWatch.Stop(); Console.WriteLine(stopWatch.ElapsedMilliseconds); } 

What I did here is to create a method for checking the performance of some elements of my code when debugging. Here is an example of how you use it:

 Utilities.PerformanceTest(someObject.SomeCustomExtensionMethod(),1000000); 

Question

The PerformanceTest method expects a function of a known type to be passed (entered). But what if I want PerformanceTest to allow various functions to be returned that return different types? How to do it?

+7
source share
3 answers

Isn't that just common?

 public static void PerformanceTest<T>(Func<T> func, int iterations) { var stopWatch = Stopwatch.StartNew(); for (int i = 0; i < iterations; i++) { T x = func(); } stopWatch.Stop(); Console.WriteLine(stopWatch.ElapsedMilliseconds); } 

Also, if you don't care about what type is the argument, you can pass Func<object> , right?

+9
source

I would change your PerformanceTest method to this:

 public static void PerformanceTest(Action func, int iterations) 

End call:

 Utilities.PerformanceTest(() => someObject.SomeCustomExtensionMethod(),1000000); 

This is likely to increase time due to lambda expression, but I can’t say how important or important it is,

+6
source

Use generics:

 public static void PerformanceTest<T>(Func<T> func, int iterations) { var stopWatch = new Stopwatch(); stopWatch.Start(); for (int i = 0; i < iterations; i++) { var x = func(); } stopWatch.Stop(); Console.WriteLine(stopWatch.ElapsedMilliseconds); } 
+2
source

All Articles