Establish the use of generic incoming and return the generic list (List (Of T))
Dotblogs label: VB.Net, with the Notes
Member practice today please turn into the DataTable List, but do attribute of the <-> corresponding field, the result of member So now, told me that having problems, he did not know how to build a list of generics, I clearly remember the results should be CreateInstance method, but how can not remember how to do it> <. Finally found out a long time ago to write the Sample Code, you'd better write it down, otherwise the next time they're looking for a long time ......
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
Program focus is: with Activator.CreateInstance to Come!
----------------
91 great reminder of better wording, conditional constraint with generic way, do not have a particular target when a parameter and then New, big thank ~~ procedure is amended as follows:
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
--------
nothing special -
but only some notes
Original: Large column using the incoming generic build and return a generic list (List (Of T))