我试图能够将一个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)'函数,对吧? –