I’m trying to write a class which can handle many different types of inputs, all of which implement the same interface.
I have the following code:
private IEnumerable<IPlan> DevisePlans(ITile tile, IEnumerable<ISpace> spaces)
{
MethodInfo method = GetType().GetMethod("DevisePlans",
BindingFlags.NonPublic | BindingFlags.Instance,
null,
new[] {tile.GetType(), typeof(ISpace)},
null);
var type = typeof(Func<,,>).MakeGenericType(tile.GetType(), typeof(ISpace), typeof(IEnumerable<IPlan>));
var planner = Delegate.CreateDelegate(type, this, method);
return spaces.SelectMany(s => (IEnumerable<IPlan>)planner.DynamicInvoke(tile, s));
}
There are lots of various implementations of DevisePlans within the class, each with a first parameter type that implements ITile.
private IEnumerable<IPlan> DevisePlans(Foo tile, ISpace space) { /* ... */ }
private IEnumerable<IPlan> DevisePlans(Bar tile, ISpace space) { /* ... */ }
This works, but I’m calling DynamicInvoke for every single iteration of my enumerable. Even if I can’t completely avoid the dynamic call, is there any way to optimize this method so that the dynamic invocation no longer resides within my loop?
It looks like you are using this to call the most specific overload (not override) of
DevisePlansfor thetileprovided. Assuming my understanding is correct (please do tell me if I’m wrong), then just usedynamic– it has an inbuilt cache and is optimized for this:and… that’s it!
I would, however, be tempted to look for an answer involving either polymorphism (against
ITile) or C# 4.0 variance.