【问题标题】:Creating a Generic List of a specified type创建指定类型的通用列表
【发布时间】:2010-05-26 16:15:24
【问题描述】:

我想创建一个通用列表 - 但我想在运行时指定类型 - 有没有办法可以做到这一点?也许使用反射?

这样的……

Public Shared Sub create(ByVal t As Type) 

  Dim myList As New Generic.List(Of t)

End Sub

提前致谢

詹姆斯

【问题讨论】:

  • 那么在这种情况下试试 System.Reflection.Emit。

标签: vb.net list generics


【解决方案1】:

如果调用者知道类型,您可以将方法本身设为通用:

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

如果调用者不知道类型,您将不得不求助于反射 - see the accepted answer to this question 了解更多信息。

【讨论】:

    【解决方案2】:

    我有一个功能可以做到这一点:

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

    例如,我可以这样创建一个整数列表:

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

    或者创建一个文本框列表:

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

    或者一般来说,任何类型。

    【讨论】:

      猜你喜欢
      • 2022-11-07
      • 1970-01-01
      • 2011-10-22
      • 1970-01-01
      • 2012-08-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多