c# Array of delegate references
When referencing other classes we use delegates. During unit testing we override these values.
I have a class which references over 20 other classes, so I thought I'd create an 开发者_运维问答array of delegates. If I create a static array of these delegates (see code below) it stores the values of the delegates, not the reference to the delegate.
As a result the unit tests can't update the values. To work around this I've created the array of delegates when I want to use them but I'd like the code below to work.
private static Func<int, bool> firstMethod = ExternalClass1.Method;
private static Func<int, bool> secondMethod = ExternalClass2.Method;
private static Func<int, bool> thirdMethod = ExternalClass3.Method;
private static Func<int, bool>[] handlers = { first, second, third };
public bool Test(int value)
{
foreach (var handler in handlers)
{
if (handler.Invoke(value) == true)
{
return true;
}
}
return false;
}
Instead of creating this handlers array, you can do something like this:
private static IEnumerable<Func<int,bool>> GetHandlers()
{
yield return firstMethod;
yield return secondMethod;
yield return thirdMethod;
}
Now you have a way to get the actual field references so they can be replaced for unit tests, but also have a way to iterate over all of the handlers. That said, an array of delegates that can be replaced is basically an interface or set of abstract methods that can be overridden. It might be cleaner and easier to maintain if you implement polymorphism using the language features designed to provide it. For the convenience of swapping out behavior using delegates during your unit tests, you can use mocking frameworks like Moq to mock an interface without having to write specific test classes.
-Dan
精彩评论