This is a dirty thing and I feel dirty for this:
public abstract class InterestRate {
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 CompoundedInterestRatederived from an abstract class InterestRate. I have several specific implementations NonCompoundedInterestRatethat have static methods with a name ImpliedRatewith the appropriate signature for the above reflection to work.
Using reflection to invoke a static method, which is not even guaranteed to be present in a derived class, just smells. Is there a better way to handle this?
source
share