开发者

Creating a Generic List of a specified type

I want to create a generic list - but I want to specify the type at runtime - is there a way I can do this? using reflection perhaps?

Something like this...

Public Shared Sub create(ByVal 开发者_开发百科t As Type) 

  Dim myList As New Generic.List(Of t)

End Sub

Thanks in advance

James


If callers know the type, you can make the method itself generic:

Public Shared Sub create(Of t)() 
    Dim myList As New Generic.List(Of t)
End Sub

If callers do not know the type, you'll have to resort to reflection - see the accepted answer to this question for more information.


I have a function to do exactly that:

Public Shared Function CreateList(Of T)(ByVal ParamArray items() As T) As List(Of T)
    Return New List(Of T)(items)
End Function

For instance, I can create a list of integers by doing this:

dim L as list(of Integer) = CreateList(1,2,3,4,5)

Or create a list of, say, textboxes:

dim L as list(of TextBox) = CreateList(txtPhone1, txtPhone2, txtPhone3)

Or in general, any type.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜