我試圖能夠將一個Type參數傳遞給名爲ConvertList的函數,並讓該函數創建指定類型的某些實例。所以,如果我傳入Foo類型,函數將創建Foo類型的新對象,並將創建的對象放入自定義List對象(SLMR_OBjList)中。將參數傳遞給泛型類型VB.Net中的新構造函數泛型
功能是定義一個通用類:
Public Class BOIS_Collection_Base(Of T)
功能將接受比什麼是類定義了其他類型。所以,如果我們創建一個BOIS_Collection_Base(Of MyTypeA)
的實例,我們可以調用函數ConvertList(Of MyTypeB)
。
我想私有變量_convertedList是一個不同於類的類型。這可能嗎?我似乎只能用(T)來定義它。
這是我到目前爲止有:
Public Class BOIS_Collection_Base(Of T)
Private _convertedList As SLMR_ObjList(Of T) ' I can only seem to define this as (Of T), but want to make sure I can pass in a Type other than the Base(Of T)
Public Function ConvertedObjList(Of myT)() As SLMR_ObjList(Of T) ' Should this be (Of T) or (Of myT) since I want it to use whatever Type is passed in
For Each tempVar In Me.ObjList
Dim newitem As myT = Activator.CreateInstance(GetType(myT), tempVar)
' Next line won't compile, says on newitem 'Value of type 'myT' cannot be converted to 'T'
_convertedList.Add(newitem)
Next
_convertedList.Sort_Direction = Me.Sort_Direction
_convertedList.Sort_Expression_List = Me.Sort_Expression_List
Return _convertedList
End Function
這裏是我想能夠做到:
Dim mainCollInstance As New BOIS_Collection_Base(Of MyTypeA)
....
'Code that populates the BOIS_Collection_Base.ObjList property with an SLMR_ObjList(Of MyTypeA)
....
' Now I want to take that ObjList, and cast all the items in it to MyTypeB
Dim newListObj As SLMR_ObjList(Of MyTypeB) = mainCollInstance.ConvertList(Of MyTypeB)
這可能嗎?我錯了嗎?
針對Plutonix:
如果我定義_convertedList的方法中,像這樣:
Public Function ConvertedObjList(Of myT)() As SLMR_ObjList(Of myT)
Dim _convertedList = New SLMR_ObjList(Of myT)
我的錯誤去了,和方法我想要做什麼,但_convertedList不再是持續性的目的。
我不確定這是泛型的問題,但你如何實現繼承。如果'MyTypeA'和'MyTypeB'相關,那麼集合類可能應該是'(Of AB_BaseClass)'。更重要的是,如果他們是相關的,那麼它應該很容易從另一個自己創建一個實例:'newItem = New myTypeA(myTypeB)' – Plutonix
我不知道我明白了。請查看更新。 –
如果你想保存它,這意味着你總是將相同的類型傳遞給'ConvertedObjList(Of T)'函數,對吧? –