Refactoring Code to avoid Type Casting

后端 未结 6 1528
鱼传尺愫
鱼传尺愫 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:35

    Make the concrete implementations of IBusiness visitable by visitor pattern. then create a visitor in the investment return domain that can visit each business, like this:

    public interface IVisitor
    {
        T Visit(IIntellectualRights bus);
        T Visit(IRetailBusiness bus);
    }
    
    public interface IBusiness
    {
        T Accept(IVisitor visitor);
    }
    
    public class AudioCDShop : EntityBaseClass, IRetailBusiness
    {
         public void Accept(IVisitor visitor)
         {
              return visitor.Visit(this);
         }
    
    //do the same for each IBusiness implementor.
    

    Then in your investment return domain:

     public class InvestmentVisitor : IVisitor
     {
         public InvestmentReturn GetInvestment(IBusiness bus)
         {
              return bus.Accept(this);
         }
    
         public InvestmentReturn Visit(IIntellectualRights bus)
         {
              return new IntellectualRightsInvestmentReturn(bus)
         }
    
         public InvestmentReturn  Visit(IRetailBusiness bus)
         {
              return new RetailInvestmentReturn(bus);
         }
     }
    

    Usage

     var investmentReturn = new InvestmentVisitor().GetInvestment(bus);
    

    totally untested and unverified.. but the concept works. This might also be way overkill if you only have two different kinds of nodes that should be visited.

提交回复
热议问题