I have a couple of utility methods I would like to add to a solution on which I am working and use of dependency injection would open many more potential uses of said methods.
I am using C#, .NET 4
Here is an example of what I am 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 have done here is create a method to test the performance of certain elements of my code when debugging. Here is an example of how you would use it:
Utilities.PerformanceTest(someObject.SomeCustomExtensionMethod(),1000000);
The "PerformanceTest" method expects to be passed (injected) a function of known type. But what if I want "PerformanceTest" to allow injection of various functions that return various types? How do I do that?
Can't it be just generic?
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 of what type is the argument, you can pass Func<object>
, can't you?
I would change your PerformanceTest method to this:
public static void PerformanceTest(Action func, int iterations)
End than call:
Utilities.PerformanceTest(() => someObject.SomeCustomExtensionMethod(),1000000);
This will probably increase the time, because of lambda expression, but I can´t say how or if this is even important,
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With