Refactoring Code to avoid Type Casting

后端 未结 6 1515
鱼传尺愫
鱼传尺愫 2020-12-09 13:04

I have following C# code in .Net 4.0. It requires a type casting of IBusiness to IRetailBusiness.

//Type checking
if (bus is IRetailBusiness)
{
       //Typ         


        
6条回答
  •  失恋的感觉
    2020-12-09 13:32

    Basically, if I understood you right, you want to avoid the type casting.

    You can accomplish that simply by changing the constructor signature from:

    public RetailInvestmentReturn(IRetailBusiness retail) {...}
    public IntellectualRightsInvestmentReturn(IIntellectualRights intellectual) {...}
    

    to:

    public RetailInvestmentReturn(IBusiness retail) {...}
    public IntellectualRightsInvestmentReturn(IBusiness intellectual) {...}
    

    If that is not an option due to design constraints, then you can try to use the strategy pattern. That would still need a type cast, but you would get rid of the terrifying "ifs" and "elses", that, I believe, is your real question, right? In order to do that you need to:

    1. Create a dictionary with the "type" and the "method to run"
    2. Use it!

    In code, that would look something like this:

    1. (Create,...)

          Dictionary> dict = new Dictionary>
          {
              {typeof (BookShop), business => new RetailInvestmentReturn((IRetailBusiness) business)},
              {typeof (AudioCDShop), business => new IntellectualRightsInvestmentReturn((IIntellectualRights) business)}
          };
      
    2. (Use it!)

    // try this:

    foreach (IBusiness bus in allMyProfitableBusiness)
    {
        investmentReturns.Add(dict[bus.GetType()](bus));
    }
    

提交回复
热议问题