2016-03-18 128 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'。 –