我想知道的是确定哪个子类实际传入函数的最佳表现。
以下是我将介绍最佳性能的三种不同方式: (ACHData,CCData和DC数据都从BaseData继承)
public BaseProcessor GetProcessor(BaseData paymentInfo)
{
if (paymentInfo.GetType() == typeof(ACHData))
{
return GetACHProcessor((ACHData)paymentInfo);
}
else if (paymentInfo.GetType() == typeof(CCData))
{
return GetCCProcessor((CCData)paymentInfo);
}
else if (paymentInfo.GetType() == typeof(DCData))
{
return GetDCProcessor((DCData)paymentInfo);
}
else
{
throw new Exception(ExceptionMessage);
}
}
public BaseProcessor GetProcessor(BaseData paymentInfo)
{
if (paymentInfo is ACHData)
{
return GetACHProcessor((ACHData)paymentInfo);
}
else if (paymentInfo is CCData)
{
return GetCCProcessor((CCData)paymentInfo);
}
else if (paymentInfo is DCData)
{
return GetDCProcessor((DCData)paymentInfo);
}
else
{
throw new Exception(ExceptionMessage);
}
}
public BaseProcessor GetProcessor(BaseData paymentInfo)
{
var achInfo = paymentInfo as ACHData;
if (achInfo != null)
{
return GetACHProcessor(achInfo);
}
var ccInfo = paymentInfo as CCData;
if (ccInfo != null)
{
return GetCCProcessor(ccInfo);
}
var dcInfo = paymentInfo as DCData;
if (dcInfo != null)
{
return GetDCProcessor(dcInfo);
}
throw new Exception(ExceptionMessage);
}
答案 0 :(得分:4)
我会重新思考你的整个设计。让您的类实现一个界面,迫使他们选择要作为处理器提供的内容:
public interface IKnowWhatProcessorIWant {
IProcessor CreateProcessor();
}
public class ACHData : BaseData, IKnowWhatProcessorIWant {
public IProcessor CreateProcessor() {
return new GetACHProcessor(this);
}
}
然后您的GetProcessor
代码变为:
public BaseProcessor GetProcessor(IKnowWhatProcessorIWant obj) {
return obj.CreateProcessor();
}
...或者,你可以完全省略那个方法。