相关疑难解决方法(0)

重构代码以避免类型转换

我在.Net 4.0中有以下C#代码.它需要对IRetailBusiness进行IBusiness类型转换.

//Type checking
if (bus is IRetailBusiness)
{
       //Type casting
       investmentReturns.Add(new RetailInvestmentReturn((IRetailBusiness)bus));
}

if (bus is IIntellectualRights)
{
       investmentReturns.Add(new IntellectualRightsInvestmentReturn((IIntellectualRights)bus));
}
Run Code Online (Sandbox Code Playgroud)

业务场景:

我正在为投资控股公司设计软件系统.该公司拥有零售业务和IntellectualRights业务.BookShop和AudioCDShop是零售业务的例子.EngineDesignPatent和BenzolMedicinePatent是IntellectualRights业务的例子.这两种业务类型完全不相关.

投资公司有一个概念叫InvestmentReturn (但每个企业对这个概念完全无知).InvestmentReturn是从每个业务获得的利润,并使用它进行计算ProfitElement.对于每种"业务类型"(Retail,IntellectualRights),使用的ProfitElement是不同的.

如何重构这个一流的设计,以避免这种情况type castingtype checking

摘要投资

public abstract class InvestmentReturn
{
    public double ProfitElement { get; set; }
    public IBusiness Business{ get;  set; }

    public abstract double GetInvestmentProfit();

    public double CalculateBaseProfit()
    {
       double profit = 0;

       if (ProfitElement < 5)
       {
           profit = ProfitElement * 5 / 100; …
Run Code Online (Sandbox Code Playgroud)

c# generics design-patterns domain-driven-design visitor

8
推荐指数
1
解决办法
3432
查看次数