关于继承和OOP c#的问题

本文关键字:OOP 问题 于继承 继承 | 更新日期: 2023-09-27 18:04:41

我有一个持久对象,为了解决这个问题,我将其命名为car类。

public class Car
{
   public string model {get;set}
   public int year {get;set}
}

显然大大简化了。

现在,随着代码的开发,我自然创建了一个接受CAR作为参数的函数。例如:
public void PaintCar (Car theCar)
{
  //Does some work
}

到目前为止都很好,但是后来我有一个场景,我需要另一个类,它非常类似于CAR,但是CAR缺少一些字段。没有问题,我认为OOP可以拯救我,我只需要继承Car,以:

结束
public class SuperCar : Car
{
   public string newProp {get;set}
   // and some more properties
}

再一次,一切看起来都很美好,直到我遇到了一个非常有用的实用函数,我用它来填充car的原始属性。

Public void SetCarProperties(Car theCar)
{
    //sets the properties for car here
}

我想,嗯,我希望我可以使用相同的函数来设置我的superCar类的属性,而不需要重写。我也不想更改基本汽车定义以包含superCar类的所有属性。

在这一点上,我陷入了两难的境地。重写会起作用,但这是额外的工作。有没有更优雅的解决方案。基本上,我想通过超类传递到一个期望基类的函数。这在c#中可能吗?我的最终代码结果是这样的:
Car myCar = new Car(); 
SetCarProperties(myCar); // ALL GOOD
SuperCar mySuperCar = new SuperCar(); 
SetCarProperties(mySuperCar); // at the moment this function is expecting type Car...

关于继承和OOP c#的问题

一个更优雅的解决方案是将函数SetCarProperties放在Car类上,并在SuperCar中覆盖它,使用base来填充Car的属性,并使用一些额外的代码来填充SuperCar属性。

编辑:也称为多态性

引入重写,但让原始调用基类版本来设置公共属性:

public void SetCarProperties(Car car)
{
    // set general properties
}
public void SetCarProperties(SuperCar veyron)
{
    this.SetCarProperties((Car) veyron);
    // SuperCar specific properties
}

你应该在Car类中用protected virtual创建一个方法。每个子类想要设置自己的任何属性都可以在这个函数中完成。因此,您的代码可以如下所示:

   public class Car
   {
      public string model {get;set}
      public int year {get;set}
      public void SetCarProperties(Car theCar)
      {
          //sets the properties for car here
         ….
        //at the end:
          SetExtraProperties();
       }
      protected virtual void SetExtraProperties()
      {
      }
  }

在任何想要设置自己属性的子类中,它必须重写方法as:

    public class SuperCar : Car
     {
      public string newProp {get;set}
       // and some more properties
      protected override void SetExtraProperties()
       {
       this.newProp = "";
        …
       }
     }

car = car as SuperCar;if (sCar != null){设置疤痕属性;}