运行 Car c=new Driver();在 C# 中

发布于 2024-10-06 00:08:44 字数 145 浏览 2 评论 0原文

假设我们有两个类 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

滿滿的愛 2024-10-13 00:08:45

尽管引用 c 指向 Driver 对象,但引用的类型 (Car) 决定了可以对其调用哪些方法。

附带说明一下,将 Driver 作为从 Car 派生的类没有多大意义。类继承通常可以表示为“is-a”关系,而大多数驱动程序都不是汽车。

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.

层林尽染 2024-10-13 00:08:45

如果您确定 Car 实际上是 Driver,那么您可以将其转换为 driver 以访问 Driver< 的成员/代码>。因此,

((Driver)c).DriverMember();

如果c不是Driver,这将抛出异常

,或者

Driver d = c as Driver;
if( d != null ){
  d.DriverMethod();
}

原因是因为cCar类型code>,则只有Car的会员可用。

例如,假设您有 List,其中添加了一些 Car 对象和一些 Driver 对象。那么它就给出了只有 Car 的成员才可以使用的完美感觉。

另外,在这种情况下,我假设 Driver 继承自 Car (这实际上是一个非常奇怪的继承,因为驱动程序不是汽车)。

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).

甜警司 2024-10-13 00:08:45

就您而言,汽车是驱动程序的基类。这就是为什么您可以创建一个新的驱动程序对象,但将它们“放入”汽车对象中。

但是,只有“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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文