This is a good example of the drawbacks of static methods.
If you can, convert these static methods to instance methods (perhaps of some new worker class, with a static factory method to return the instance, or use IOC). Then you'll have much more flexibility to use inheritance to avoid repeating code.
UPDATE
After some feedback, I had a think and it is possible, kind of. Use reflection to get the parameter lists for all the versions of B, and compare with the parameter list of D.
public static int D(params object[] paramArray)
{
var paramTypes = paramArray.Select(x => x.GetType());
var method = typeof(Static.A).GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.FlattenHierarchy)
.Where(m => m.Name == "B" && m.GetParameters().Select(x => x.ParameterType).SequenceEqual(paramTypes))
.FirstOrDefault();
if (method != null)
{
return (int)method.Invoke(null, paramArray);
}
throw new Exception("Overloaded method not found");
}
The downside of this approach is that there is no compile-time checking of parameters, no Intellisense, etc. I can't think of a way of getting round this without repeating the specification of each version of A.B()
, like this:
private static int GenericD(object[] paramArray, MethodBase caller)
{
var paramTypes = caller.GetParameters().Select(x => x.ParameterType);
var method = typeof(Static.A).GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.FlattenHierarchy)
.Where(m => m.Name == "B" && m.GetParameters().Select(x => x.ParameterType).SequenceEqual(paramTypes))
.FirstOrDefault();
if (method != null)
{
return (int)method.Invoke(null, paramArray);
}
throw new Exception("Overloaded method not found");
}
public static int D(string p)
{
object[] paramArray = new object[] { p };
return GenericD(paramArray, MethodInfo.GetCurrentMethod());
}
public static int D(string p, int x)
{
object[] paramArray = new object[] { p, x };
return GenericD(paramArray, MethodInfo.GetCurrentMethod());
}
In this solution, each version of D() is almost identical, but not quite. Ideally you would want some way of programmatically converting a method's parameter list into an object[]
, but there doesn't seem to be an easy way to do that.