运行 Car c=new Driver();在 C# 中
假设我们有两个类 Car 和 Driver,,
我们能够创建类似的对象
Car c=new Driver();
并且能够调用 Car 类的成员,但不能调用 Driver 类的成员,为什么以及何时? ?
suppose we've two classes Car and Driver,,
and we are able to make object like
Car c=new Driver();
and able for calling members of Car Class but not of Driver Class Why and When ? ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尽管引用
c
指向Driver
对象,但引用的类型 (Car
) 决定了可以对其调用哪些方法。附带说明一下,将
Driver
作为从Car
派生的类没有多大意义。类继承通常可以表示为“is-a”关系,而大多数驱动程序都不是汽车。Even though the reference
c
points to aDriver
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 fromCar
does not make much sense. Class inheritance usually can be expressed as a "is-a" relationship, and most drivers are not cars.如果您确定
Car
实际上是Driver
,那么您可以将其转换为driver
以访问Driver< 的成员/代码>。因此,
如果
c
不是Driver
,这将抛出异常,或者
原因是因为
c
是Car
类型code>,则只有Car的会员可用。例如,假设您有
List
,其中添加了一些Car
对象和一些Driver
对象。那么它就给出了只有Car
的成员才可以使用的完美感觉。另外,在这种情况下,我假设
Driver
继承自Car
(这实际上是一个非常奇怪的继承,因为驱动程序不是汽车)。If you are sure that
Car
is actually aDriver
, then you can cast it to adriver
to access the members ofDriver
. So eitherThis will throw an exception if
c
is not aDriver
Or
The reason is that since
c
is of typeCar
, then only Car's members are available.For example, let's say you have
List<Car>
where you add someCar
objects and someDriver
objects. Then it gives perfect sense that onlyCar
's members are possible to use.Also, I assume that
Driver
inherit fromCar
in this case (which is actually a pretty strange inheritance since a driver is not a car).就您而言,汽车是驱动程序的基类。这就是为什么您可以创建一个新的驱动程序对象,但将它们“放入”汽车对象中。
但是,只有“car”类的成员可见的原因是,您的对象 c 来自 Car 类型,而不是来自 Driver 类型,并且 Car 的成员少于 Driver。
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.