Vb.net 将对象强制转换回原始类型

Vb.net 将对象强制转换回原始类型,vb.net,list,casting,derived-class,Vb.net,List,Casting,Derived Class,我在列表(BodyComponent)中有对象BodyComponent是一个基类,添加到列表中的项目是来自派生类的对象 Public Class Body_Cylinder ' Get the base properties Inherits BodyComponent ' Set new properties that are only required for cylinders Public Property Segments() As Integer Public Property

我在
列表(BodyComponent)
中有对象
BodyComponent
是一个基类,添加到列表中的项目是来自派生类的对象

Public Class Body_Cylinder

' Get the base properties
Inherits BodyComponent

' Set new properties that are only required for cylinders
Public Property Segments() As Integer
Public Property LW_Orientation() As Double End Class
现在,我想将对象转换回其原始类
Body\u圆柱体
,以便用户可以为对象输入一些特定于类的值

但是我不知道怎么做这个操作,我找了一些相关的帖子,但是这些都是用
c#
写的,我对此一无所知

我想答案可能在这里,但是。。无法读取它

您可以使用LINQ方法:

Dim cylinders = bodyComponentList.OfType(Of Body_Cylinder)()
For Each cylinder In cylinders
    '  set the properties here '
Next
该列表可以包含继承自
BodyComponent
的其他类型

三件事也是如此:

  • 检查对象是否为
    主体(圆柱体)类型
  • 筛选出所有不属于该类型和
  • 将它投射到它身上。因此,您可以安全地使用循环中的属性
  • 如果你已经知道该对象,为什么不直接将其投射?使用
    CType
    DirectCast

    Dim cylinder As Body_Cylinder = DirectCast(bodyComponentList(0), Body_Cylinder)
    
    如果需要预先检查类型,可以使用-

    或:

    您可以使用LINQ方法:

    Dim cylinders = bodyComponentList.OfType(Of Body_Cylinder)()
    For Each cylinder In cylinders
        '  set the properties here '
    Next
    
    该列表可以包含继承自
    BodyComponent
    的其他类型

    三件事也是如此:

  • 检查对象是否为
    主体(圆柱体)类型
  • 筛选出所有不属于该类型和
  • 将它投射到它身上。因此,您可以安全地使用循环中的属性
  • 如果你已经知道该对象,为什么不直接将其投射?使用
    CType
    DirectCast

    Dim cylinder As Body_Cylinder = DirectCast(bodyComponentList(0), Body_Cylinder)
    
    如果需要预先检查类型,可以使用-

    或:


    如果你知道类型,你可以使用。CType(列表(0),主体\圆柱体)。分段=0链接指的是与您想要的略有不同的装箱。由于基具有itemtype属性,因此使用该属性可以知道它是哪一个,然后
    CType
    进行转换。如果知道类型,则可以使用。CType(列表(0),主体\圆柱体)。分段=0链接指的是与您想要的略有不同的装箱。由于基类有一个itemtype属性,因此使用该属性可以知道它是什么,然后使用
    CType
    进行转换。感谢您的回复,但这并不完全是我想要的,我确切地知道我需要从基类转换到deriverd类的对象。我想这样做,这样我就可以打开并将这个对象及其属性值加载到带有文本框的表单中。@Mech_Engineer:如果你已经知道了,为什么不强制转换它?使用
    CType
    DirectCast
    。感谢您的回复,但这并不完全是我想要的,我确切地知道需要从基类转换到deriverd类的对象。我想这样做,这样我就可以打开并将这个对象及其属性值加载到带有文本框的表单中。@Mech_Engineer:如果你已经知道了,为什么不强制转换它?使用
    CType
    DirectCast