这是一件肮脏的事情,我为此感到肮脏:
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 }
);
}
在这里,我有类NonCompoundedInterestRate
(抽象)并CompoundedInterestRate
派生自抽象类InterestRate
。我有几个具体的实现,NonCompoundedInterestRate
它们具有使用适当签名命名的静态方法ImpliedRate
,以使上述反射起作用。
使用反射来调用甚至不能保证在派生类上存在的静态方法只是臭气熏天。有没有更好的方法来处理这个?