0

我知道超类可以存储子类的实例,

例如:

public class Subclass
{
   private int color;

   public Subclass()
   {
     color = "red";
   }
}

Superclass v = new Subclass();

超类不知道子类中的方法、变量等,但通过转换它,您可以访问这些。

这是如何运作的?

例子:

Vechicle v = new Car();
Car c = (Car) v;
Consoel.WriteLine(c.color);


Output:
red
4

1 回答 1

1

It is not as simple as you have specified.

if color is changed in constructor of Car it will be different than red.

Further there is concept of virtual methods.

Following is not inheritance but casting. Inheritance msdn

Car c = (Car) v;

All inherited types can be type-casted to base type, but it is not necessary. In addition there can be user defined conversions, and conversions with helper class.
Casting and Type Conversion - MSDN

于 2013-11-02T04:43:09.610 回答