利用傳入的泛型建立並回傳泛型清單(List(Of T))

  • 3615
  • 0
  • 2012-03-31

利用傳入的泛型建立並回傳泛型清單(List(Of T))

Dotblogs 的標籤: ,

今天請 Member 練習把 DataTable 轉成 List,而且要做屬性<->欄位的對應,結果 member 搞了半天,跟我說遇到問題,他不知道要怎麼建立泛型清單,結果我明明記得應該是 CreateInstance 方法,但卻怎樣都想不起該怎麼做 ><。搞半天終於找到以前寫的 Sample Code,所以還是趕快筆記下來,不然下次又要找半天……

Module Module1

    Sub Main()
        Dim PersonList = ToGenericList(New Person())
        PersonList.Item(0).Name = "XYZ"
        PersonList.Item(1).Name = "Leo"
        For Each p In PersonList
            Console.WriteLine(p.Name)
        Next

        Console.ReadLine()
    End Sub

    Public Function ToGenericList(Of T)(ByVal entity As T) As List(Of T)
        Dim GenericList As New List(Of T)
        Dim p1 As T = CType(Activator.CreateInstance(GetType(T)), T)
        GenericList.Add(p1)
        Dim p2 As T = CType(Activator.CreateInstance(GetType(T)), T)
        GenericList.Add(p2)

        Return GenericList
    End Function

End Module

Public Class Person
    Public Name As String
    Public Age As Integer
End Class

程式碼重點就是:用 Activator.CreateInstance 就行啦!

----------------

91 大提醒了更好的寫法,用泛型條件約束的方式,就不用特別再 New 一個物件當參數,大感謝~~ 程式碼修正如下:

Module Module1

    Sub Main()
        Dim PersonList = ToGenericList(Of Person)()
        PersonList(0).Name = "XYZ"
        PersonList(1).Name = "Leo"
        For Each p In PersonList
            Console.WriteLine(p.Name)
        Next

        Console.ReadLine()
    End Sub

    Public Function ToGenericList(Of T As New)() As IEnumerable(Of T)
        Dim GenericList As New List(Of T)
        GenericList.Add(New T)
        GenericList.Add(New T)

        Return GenericList
    End Function

End Module

Public Class Person
    Public Name As String
    Public Age As Integer
End Class

 

--------
沒什麼特別的~
不過是一些筆記而已