1

我正在为我的程序的一部分构建一个 MVC 结构。

我已经完成了 5-10 个表的模型,它们的共同点只是构造函数。(采用recordset.fields)

这是我填充这些对象的函数:

Public Function reqTable(ByVal pTable As String, ByVal pType As Type, ByVal pNoProjet As Integer, Optional ByVal strAdditionnalConditions As String = "") As List(Of Object)
    Dim lstRetour As List(Of Object) = New List(Of Object)

    rsRequestCSV = conSQL.Execute("SELECT * FROM " & pTable & " WHERE NoProjet = " & pNoProjet & " " & strAdditionnalConditions)
    With rsRequestCSV
        While Not .EOF
            lstRetour.Add(Activator.CreateInstance(pType, New Object() {rsRequestCSV.Fields})) 'New clsTable(rsRequestCSV.Fields))
            .MoveNext()
        End While
    End With
    Return lstRetour
End Function

我无法实现的是返回 List(Of pType) 而不是 List(Of Object)。

我想要这个的原因是在我的数据网格视图中有标题,即使它们是空的。

那么有没有办法返回 List(Of MyModel'sType) ?

提前致谢!

4

2 回答 2

2

只需使用As pType代替As Object(但考虑使用常规类型参数名称,即T代替pType),删除现在已过时的pType参数,并使用以下内容创建和添加实例:

Public Function ReqTable(Of T)(ByVal table As String, ByVal noProject As Integer, Optional ByVal additionalConditions As String = "") As List(Of T)
    Dim result As New List(Of T)()

    ' Where is this declared?! It probably should be declared here.
    request = conSQL.Execute( _
        String.Format("SELECT * FROM {0} WHERE NoProjet = {1} {2}", _
                      table, noProjet, additionnalConditions))

    While Not request.EOF
        result.Add( _
            CType(Activator.CreateInstance( _
                    GetType(T), New Object() {request.Fields}), _
                T))
        request.MoveNext()
    End While

    Return result
End Function

GetTpe(T) gets you a System.Type instance representing the type argument. Since VB, unlike Java, has reified generic types you can thus create instances from type argument.

Apart from that, pay attention that .NET has different code style conventions than Java; for instance, all methods should use PascalCase, not camelCase. And like in Java, use of Hungarian notation is discouraged. Use concise but descriptive names. And, as Rene noted, your code suffers from an SQL injection vulnerability.

于 2012-08-07T13:32:03.350 回答
1

忽略 SQL 注入问题,试试这个:

Public Function reqTable(of T)(ByVal pTable As String, ByVal pNoProjet As Integer, Optional ByVal strAdditionnalConditions As String = "") As List(Of T)
    Dim lstRetour As New List(Of T)

    rsRequestCSV = conSQL.Execute("SELECT * FROM " & pTable & " WHERE NoProjet = " & pNoProjet & " " & strAdditionnalConditions)
    With rsRequestCSV
        While Not .EOF
            lstRetour.Add(Activator.CreateInstance(T, New Object() {rsRequestCSV.Fields})) 'New clsTable(rsRequestCSV.Fields))
            .MoveNext()
        End While
    End With
    Return lstRetour
End Function
于 2012-08-07T13:07:34.850 回答