running Car c=new Driver(); in C#
suppose we've two classes Car and Driver,,
and we are able to make object likeCar c=new Driver();
and able for calling members of Ca开发者_如何学运维r Class but not of Driver Class Why and When ? ?
Even though the reference c
points to a Driver
object, the type of the reference (Car
) determines which methods can be called on it.
As a side note, having Driver
as a class derived from Car
does not make much sense. Class inheritance usually can be expressed as a "is-a" relationship, and most drivers are not cars.
If you are sure that Car
is actually a Driver
, then you can cast it to a driver
to access the members of Driver
. So either
((Driver)c).DriverMember();
This will throw an exception if c
is not a Driver
Or
Driver d = c as Driver;
if( d != null ){
d.DriverMethod();
}
The reason is that since c
is of type Car
, then only Car's members are available.
For example, let's say you have List<Car>
where you add some Car
objects and some Driver
objects. Then it gives perfect sense that only Car
's members are possible to use.
Also, I assume that Driver
inherit from Car
in this case (which is actually a pretty strange inheritance since a driver is not a car).
In your case, Car is the base class of driver. This is the point why you can create a new driver object but "put" them into a Car object.
But the reason why only the member of the class "car" are visible is, that your object c is from type Car and not from type Driver and Car has less members than Driver.
精彩评论