标签:手记 遇到 sam pre func cti activator 属性 new t
利用传入的泛型建立并回传泛型清单(List(Of T))
今天请 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
--------
没什么特别的~
不过是一些笔记而已
原文:大专栏 利用传入的泛型建立并回传泛型清单(List(Of T))
标签:手记 遇到 sam pre func cti activator 属性 new t
原文地址:https://www.cnblogs.com/petewell/p/11516437.html