Let’s say I have these class hierarchy :
public abstract class Parent {
}
public class A : Parent {
public void Update() { }
}
public class B : Parent {
public void Update() { }
}
public class C : Parent {
public void Update() { }
public void Update(bool force) { }
}
As you can see, all descendant of Parent have an Update method, with no parameter.
I want to create an utility class that can work with any kind of Parent object and call Update at the end of the process. I am sure the Update method will be implemented, so I wrote this code :
public class ParentUtilities {
private static readonly Dictionary<Type, MethodInfo> g_UpdateMethods = new Dictionary<Type, MethodInfo>{
{ typeof(A), typeof(A).GetMethod("Update", new Type[] {})},
{ typeof(B), typeof(B).GetMethod("Update", new Type[] {})},
{ typeof(C), typeof(C).GetMethod("Update", new Type[] {})}
};
public static void DoSomething(Parent p)
{
CalculateTheMeaningOfTheLife(p);
g_UpdateMethods[p.GetType()].Invoke(p, null);
}
}
As I don’t have control over the class hierarchy (it’s from a 3rd party assembly). I can only change the utility class. How can I avoid such tweak ?
As I’m sticked to .Net 3.5 SP1, I can’t use dynamic.
If there’s just a known, (very) small set of child classes then you could do something like this: