stack overflow question P Peter Chajmovic to peter.chajmovic@gmail.com 4 minutes agoDetails C#, How to create an object of derived class based ctor parameters without exclicitly calling the derived
Hi, I have simplified my true issue into the following example:
'''
namespace Cars
{
public class Program
{
public static void Main(string[] args)
{
Car car1 = Car.Create(new Driver(1, "A", License.Private));
Car car2 = Car.Create(new Driver(2, "B", License.Truck));
Car car3 = Car.Create(new Driver(3, "C", License.Bus));
car1.OpenTrunk();
car2.AttachWagon();
car3.OpenBackDoor();
}
}
enum License { Private, Truck, Bus }
public class Driver
{
public uint ID { get; private set; }
public string Name { get; private set; }
public License License { get; private set; }
public Driver(uint id, string name, License license)
{
ID = id;
Name = name;
License = license;
}
}
public abstract class Car
{
protected Driver driver;
public Car(Driver driver)
{
this.driver = driver;
}
public static Car Create(Driver driver)
{
switch (driver.License)
{
License.Private: return new Private(driver);
License.Truck: return new Truck(driver);
License.Bus: return new Bus(driver);
}
}
}
public class Private : Car
{
public Private(Driver driver) : base(driver) {}
public void OpenTrunk();
}
public class Truck : Car
{
public Truck(Driver driver) : base(driver) {}
public void AttachWagon();
}
public class Bus : Car
{
public Bus(Driver driver) : base(driver) {}
public void OpenBackDoor();
}
}
'''
Let's say I have a parent class Car from which three classes derives: Private, Truck and Bus.
The constructor of the derived classes receive one parameter of class Driver.
The class Driver contain among other properties the property License.
Assuming that each driver can have a license only to one of the three types of cars (Private, Truck, Bus).
I want to create a function which will return me an object of one of the derived classes based on the Driver provided to the function.
I want the user of this function to receive an object on which he may call specific functions for each derived class such as bus1.OpenBackDoor() or truck1.AttachWagon().
What will be the best way to do so while keeping the general structure of the example code (the Create method may be called differently) ?
Aucun commentaire:
Enregistrer un commentaire