从基类创建继承的类

Raj*_*Raj 5 c# inheritance design-patterns decorator

public class Car 
{ 
    private string make;
    private string model;
    public Car(string make, string model)
    {
         this.make = make;
         this.model = model;
    }
    public virtual void Display()
    {
       Console.WriteLine("Make: {0}", make);
       Console.WriteLine("Model: {0}", model);
    }
    public string Make
    {
       get{return make;}
       set{make = value;}
    }
    public string Model
    {
       get{return model;}
       set{model = value;}
    }
}

public class SuperCar:Car
{
    private Car car;
    private int horsePower;
    public SuperCar(Car car)
    {
        this.car = car;
    }
    public int HorsePower
    {
       get{return horsePower;}
       set{horsepower = value;}
    }
    public override void Display()
    {
       base.Display();
       Console.WriteLine("I am a super car");
}
Run Code Online (Sandbox Code Playgroud)

当我做的事情

Car myCar = new Car("Porsche", "911");
SuperCar mySupcar = new SuperCar(myCar);
mySupcar.Display();
Run Code Online (Sandbox Code Playgroud)

我只得到"我是一辆超级跑车",但不是我基地的属性.我应该在SuperCar构造函数中显式分配我的基类的属性吗?事实上,我正在尝试使用Decorator模式,我想要一个类向基类添加行为.

kem*_*002 8

或者:

public class Car
{
    public Car(string make, string model)
    {
         this.make = make;
         this.model = model;
    }


    public Car (Car car):this(car.Make, Car.Model){}
}

public class SuperCar : Car
{
  SuperCar(Car car): base(car){}
}
Run Code Online (Sandbox Code Playgroud)

这样,您可以从汽车继承任何类,并从提供的对象中填充汽车内容.继承的对象不需要知道要设置什么.它们只是将当前的Car对象传递给基类,它就完成了工作.


小智 6

我可能会在这里来晚一点,但只要有人发现这个有用:

你可以使用反射.它需要比你提出的更多的代码,但我认为它仍然提供了你正在寻找的简洁性.

public SuperCar(Car car)
{
    var props = typeof(Car).GetProperties().Where(p => !p.GetIndexParameters().Any());
    foreach (var prop in props)
    {
        if (prop.CanWrite)
            prop.SetValue(this, prop.GetValue(car));
    }

    // Set SuperCarcentric properties
    // .
    // .
    // .
}
Run Code Online (Sandbox Code Playgroud)

我从你的例子中明确地写了这个,以清楚地说明这个概念,但我认为这最好是一个通用方法,可以在你的解决方案的所有类似实例中使用.

希望这可以帮助.