通用类型似乎毫无价值

时间:2013-12-09 13:03:49

标签: vb.net generics

请参阅以下代码:

Public Function ExecuteDynamicQuery(Of T As New)(ByVal sql As String, ByVal type As T) As List(Of T) Implements IGenie.ExecuteDynamicQuery
            Dim iConnectionBLL As iConnectionBLL = New clsConnectionBLL
            Dim paramValues() As DbParameter = New clsParameterValues().getParameterValues()
            Using conn As DbConnection = iConnectionBLL.getDatabaseTypeByDescription("Genie2"), _
                  rdr As DbDataReader = clsDatabaseHelper.ExecuteReader(conn, CommandType.Text, sql, paramValues)
                Dim list As List(Of T) = New List(Of T)
                While rdr.Read()
                    Dim hello As New T
                    Dim method As MethodInfo = GetType(clsType).GetMethod("PopulateDataReader")
                    method.Invoke(hello, New Object() {rdr})
                    list.Add(hello)
                End While

                Return list
            End Using
        End Function

是否有一种方法可以执行上面的SQL语句而不将类型作为参数传递。它似乎有点无意义 - 它唯一的原因是让函数知道泛型的类型。

1 个答案:

答案 0 :(得分:1)

您可以将方法更改为不具有第二个参数:

Public Function ExecuteDynamicQuery(Of T As New)(ByVal sql As String) As List(Of T) Implements IGenie.ExecuteDynamicQuery

然而:

  • 您还需要更改IGenie
  • 然后调用者需要显式指定类型参数,而不是让编译器根据参数(不再存在)推断它。