This is a dirty thing to do, and I feel dirty for doing it:
public abstract class InterestRate {
// irrelevant details
public static T ImpliedRate<T>(
double factor,
double time,
DayCounter dayCounter
) where T : NonCompoundedInterestRate {
MethodInfo methodInfo = typeof(T).GetMethod(
"ImpliedRate",
BindingFlags.Static);
return (T)methodInfo.Invoke(
null,
new object[] { factor, time, dayCounter }
);
}
public static T ImpliedRate<T>(
double factor,
double time,
DayCounter dayCounter,
Frequency frequency
) where T : CompoundedInterestRate {
MethodInfo methodInfo = typeof(T).GetMethod(
"ImpliedRate",
BindingFlags.Static);
return (T)methodInfo.Invoke(
null,
new object[] { factor, time, dayCounter, frequency }
);
}
Here I have classes NonCompoundedInterestRate
(abstract) and CompoundedInterestRate
deriving from abstract class InterestRate
. I have several a couple concrete implementations of NonCompoundedInterestRate
that have static methods named ImpliedRate
with the appropriate signature for the above reflection to work.
Using reflection to call a static method that is not even guaranteed to be there on a derived class just reeks. Is there a better way to handle this?