C Sharp中的继承

时间:2017-03-27 16:28:34

标签: c# inheritance

enter image description here

我是C#的新手,请你解释一下这句话的错误bigderive c = new bigbase();

1 个答案:

答案 0 :(得分:1)

看起来像这样:跑车是一辆带有一些额外功能的车。如果您将跑车存放在汽车现场,我们所知道的是:它是一辆汽车。但它是100%的汽车。

如果你试图将汽车存放在运动车上,我们无法确定它实际上是一辆跑车。这就是为什么这种说法是错误的。

如果您说bigbase c = new bigderivce()可行,那么bigderive 100%肯定至少bigbase +一些额外内容。

一个例子:

class Car {
  public void drive() { 
    // do stuff
  }
}
class SportsCar : Car {
  public void driveFaster() {

  }
}

Car car1 = new SportsCar();
car1.driveFast(); // this won't compile, because a Car has no driveFast() method by definition

SportsCar car2 = new SportsCar();
car2.driveFast(); // this works

SportsCar car3 = new Car(); // let's assume this compile
car3.driveFast(); // which method of Car would be called now? car3 is a Car, which has no driveFast() method by declaration.