C#: Method to return object whose concrete type is determined at runtime?

前端 未结 4 2134
小蘑菇
小蘑菇 2021-02-10 07:10

I\'m thinking about designing a method that would return an object that implements an interface but whose concrete type won\'t be know until run-time. For example suppose:

4条回答
  •  醉酒成梦
    2021-02-10 07:47

    This is a classic double dispatch problem and it has an acceptable pattern for solving it (Visitor pattern).

    //This is the car operations interface. It knows about all the different kinds of cars it supports
    //and is statically typed to accept only certain ICar subclasses as parameters
    public interface ICarVisitor {
       void StickAccelerator(Toyota car); //credit Mark Rushakoff
       void ChargeCreditCardEveryTimeCigaretteLighterIsUsed(Bmw car);
    }
    
    //Car interface, a car specific operation is invoked by calling PerformOperation  
    public interface ICar {
       public string Make {get;set;}
       public void PerformOperation(ICarVisitor visitor);
    }
    
    public class Toyota : ICar {
       public string Make {get;set;}
       public void PerformOperation(ICarVisitor visitor) {
         visitor.StickAccelerator(this);
       }
    }
    
    public class Bmw : ICar{
       public string Make {get;set;}
       public void PerformOperation(ICarVisitor visitor) {
         visitor.ChargeCreditCardEveryTimeCigaretteLighterIsUsed(this);
       }
    }
    
    public static class Program {
      public static void Main() {
        ICar car = carDealer.GetCarByPlateNumber("4SHIZL");
        ICarVisitor visitor = new CarVisitor();
        car.PerformOperation(visitor);
      }
    }
    

提交回复
热议问题