前言
机房开始之初在搜找师哥师姐的博客,偶尔看见看到不让用datatable的字样,原因很简单就是datatable和数据库的耦合太大了,需要知道每个字段在数据库中的索引值。这样就不是太方便,所以为了减小程序和数据库之间的耦合程度。下面是我程序的泛型集合的转换方法
内容:
Imports System.Collections.Generic '增加泛型的命名空间
Imports System.Reflection '引入反射 为了使用propertyinfo
'使用泛型集合对datatable进行转换,避免和数据库有太多的耦合
Public Class ConvertGenericsHelper
'将datatable转化为泛型集合
Public Shared Function convertToGenerics(Of T As {New})(ByVal dt As DataTable) As IList(Of T)
Dim myGenerics As New List(Of T) '定义最终返回的集合
Dim myType As Type = GetType(T)
Dim dr As DataRow '定义行集
Dim tempName As String = String.Empty '定义一个临时变量
'遍历datatable中的所有数据
For Each dr In dt.Rows
Dim myT As New T '定义一个实体类的对象
Dim propertys() As PropertyInfo = myT.GetType().GetProperties() '定义属性集合
Dim pr As PropertyInfo
'遍历该对象的所有属性
For Each pr In propertys
tempName = pr.Name '将属性名称赋值给临时变量
'检查datatable是否包含此列(列名==对象的属性名)
If (dt.Columns.Contains(tempName)) Then '将此属性与datatable离得明列比较,查看datatable是否包含此属性
If (pr.CanWrite = False) Then
Continue For
End If
Dim value As Object = dr(tempName)
If (value.ToString <> DBNull.Value.ToString()) Then
pr.SetValue(myT, value, Nothing)
End If
End If
Next
myGenerics.Add(myT) '添加到集合
Next
Return myGenerics
End Function
End Class
结尾:
多走几条线自然就会了