2016-03-18 129 views
1

我有List(of BodyComponent)中的对象BodyComponent是基类,添加到列表中的项目beeing是来自派生类的对象。现在投掷对象返回原始类型

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_Cylinder因此,用户可以输入对象类的一些特定的值。

但是我不知道该怎么做这个操作,我找了一些相关的帖子,但是这些全都写在c#里面我没有任何的知识。

我想答案可能是在这里,但..不能读取Link

+0

如果你知道类型,你可以使用[ CTYPE](https://msdn.microsoft.com/en-us/library/4x2877xb.aspx)。 CType(theList(0),Body_Cylinder).Segments = 0 –

+0

链接是指拳击,这是比你想要的略有不同。由于该基地有一个itemtype属性使用它来知道它是哪个,然后'CType'进行转换。 – Plutonix

回答

0

你可以使用LINQ Enumerable.OfType-方法:

Dim cylinders = bodyComponentList.OfType(Of Body_Cylinder)() 
For Each cylinder In cylinders 
    ' set the properties here ' 
Next 

列表可以包含其他类型从BodyComponent继承。

所以OfType做了三两件事:

  1. 检查对象是否为Body_Cylinder型和
  2. 过滤器所有哪些是该类型的不和
  3. 蒙上它它。所以你可以安全地使用循环中的属性。

如果您已经知道该物体,为什么不简单地施放它?可以用CTypeDirectCast

Dim cylinder As Body_Cylinder = DirectCast(bodyComponentList(0), Body_Cylinder) 

如果您需要预先检查的类型,你可以使用TypeOf -

If TypeOf bodyComponentList(0) Is Body_Cylinder Then 
    Dim cylinder As Body_Cylinder = DirectCast(bodyComponentList(0), Body_Cylinder) 
End If 

TryCast operator

Dim cylinder As Body_Cylinder = TryCast(bodyComponentList(0), Body_Cylinder) 
If cylinder IsNot Nothing Then 
    ' safe to use properties of Body_Cylinder ' 
End If 
+0

感谢您的回复,但不是我正在寻找的内容,我确切知道我需要从基类转换为deriverd类的对象。我想这样做,所以我可以打开加载这个对象的属性值到一个文本框的形式。 –

+0

@Mech_Engineer:如果你已经知道了,你为什么不施放它?可以使用'CType'或'DirectCast'。 –