如何获取对象的子类?

发布于 2024-08-22 13:23:49 字数 515 浏览 4 评论 0原文

举个例子:

Public Class Car
End Class

Public Class Vovlo
    Inherits Car
End Class

Public Class BMW
    Inherits Car
End Class

当我收到一个 Car 对象时,如何确定该 Car 对象是沃尔沃、宝马还是轿车?

我知道我可以使用 TypeOf,但是当有多个类继承自 Car 类时,这会变得有些麻烦。

编辑:

这就是我想要实现的目标:

   Public Sub DoSomething()
        Dim subClassCar As Car.SubClass = DirectCast(car, Car.SubClass)
   End Sub

如果汽车对象有子类,则 Car.CubClass 是沃尔沃或宝马;如果没有子类,则 Car.CubClass 是汽车。问题是如何获取Car.SubClass。

Given this example:

Public Class Car
End Class

Public Class Vovlo
    Inherits Car
End Class

Public Class BMW
    Inherits Car
End Class

When I receive a Car object, how can I determine if the Car object is a Volvo, a BMW or a Car?

I know I can use TypeOf, but when there are several classes that inherits from the Car class, this becomes somewhat cumbersome.

Edit:

This is what I want to acheive:

   Public Sub DoSomething()
        Dim subClassCar As Car.SubClass = DirectCast(car, Car.SubClass)
   End Sub

where Car.CubClass is either a Volvo or BMW if the car object has a subclass, or a car if it do not have a sub class. The problem is how to get the Car.SubClass.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(3

枉心 2024-08-29 13:23:49

TypeOf() 是最好的方法 - 我认为您想要采取的操作将类似于:

if (MyObject is Volvo) then
做某事();
else if (MyObject 是 BMW) then
做某事();
end if

如果您要执行的方法已经在 BMW 或沃尔沃中,那么您不需要进行任何类型检查,因为您知道您将属于正确的类别。如果根据汽车类型执行和采取操作的方法位于 Car 基类中,那么您将需要执行上述类型检查,但您只需在基类中执行此操作,而不是在每个派生类中执行此操作班级。

TypeOf() is the best way - I presume the action you want to take will look something like:

if (MyObject is Volvo) then
doSomething();
else if (MyObject is BMW) then
doSomething();
end if

If the method you want to execute is already in BMW or Volvo then you don't need to do any type-checking because you know you'll be in the right class. If the method to execute and take action based on the type of car is in the Car base class, then you will need to do the above type-checking but you'd only have to do it in the base class, not in each derived class.

二手情话 2024-08-29 13:23:49

实际上只有提到的两种选择,要么修改基类以具有虚拟 DoSomething 方法并在子类中重写它(您可以在基类中拥有默认功能,不必是抽象的),要么编写一个很大的条件语句(我真的不建议这样做,违背了 OOP)

There are really only the two choices mentioned, either you modify the base class to have a virtual DoSomething method and override it in the subclasses (you can have default functionality in the base class, doesn't have to be abstract), or you write a big conditional statement (I would REALLY not recommend that, goes against OOP)

牵你手 2024-08-29 13:23:49

这是您真正想要避免的事情。您可以通过向基类添加虚拟方法来实现此目的。在这篇文章中进行了更详细的讨论。

This is something you really want to avoid. You do so by adding virtual methods to the base class. Discussed in more detail in this article.

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