I encountered a similar problem a while ago ("how to overload static methods"), and I solved it with Reflection.
Here is my situation:
1) public abstract class AuditObject<T> : ActiveRecordBase<T> (yes, I use ActiveRecord) and
2) public class Employee : AuditObject<Employee>
In both of them, I define some static methods, for example
public static DataTable GetLookupTable(String where, Int32 topRows) { return doExtremelyCleverStuffToFetchData(where, topRows); }
(in # 2 you need public **new** static or you get a compiler warning)
Like a code when I call, for example.
DataTable myList = AuditObject<T>.GetLookupTable("inactive = 0", 100);
... and T is Employee, the static method is not "redefined", that is, the one that is executed is the method in (1), not (2).
So, in (1) I changed the static methods (in this example GetLookupTable) as follows:
public static DataTable GetLookupTable(String where, Int32 topRows) { DataTable tbl = null; Boolean hasOverride = hasMethodOverride("GetLookupTable"); if (hasOverride) { tbl = invokeStaticMethod<T>( "GetLookupTable", new Object[2] { where, topRows }) as DataTable; } else { tbl = doExtremelyCleverStuffToFetchData(where, topRows); } return tbl; }
Here's how I find out if a static method exists:
private static Boolean hasMethodOverride(String methodName) { var methodQuery = from method in typeof(T).GetMethods( BindingFlags.Static | BindingFlags.Public | BindingFlags.InvokeMethod) where method.Name == methodName select method; return methodQuery.Count() > 0; }
And this is how the override method is called:
public static Object invokeStaticMethod<T>(String MethodName, Object[] Args) { return typeof(T).InvokeMember(MethodName, BindingFlags.Public | BindingFlags.Static | BindingFlags.InvokeMethod, null, null, Args); }
Howl! When I call DataTable myList = AuditObject<T>.GetLookupTable("inactive = 0", 100); and T is Employee, I get the results of the static method defined in the Employee class.
Hope this helps,
Dimitris