下面代码是C版的,最近刚学习VB.NET,语法不太熟悉,还望大神给转化成VB.NET的,小女子不胜感激。
public static IList<T> convertToList<T>(DataTable dt) where T : new()
8 {
9 // 定义集合
10 List<T> ts = new List<T>();
11
12 // 获得此模型的类型
13 Type type = typeof(T);
14 //定义一个临时变量
15 string tempName = string.Empty;
16 //遍历DataTable中所有的数据行
17 foreach (DataRow dr in dt.Rows)
18 {
19 T t = new T();
20 // 获得此模型的公共属性
21 PropertyInfo[] propertys = t.GetType().GetProperties();
22 //遍历该对象的所有属性
23 foreach (PropertyInfo pi in propertys)
24 {
25 tempName = pi.Name;//将属性名称赋值给临时变量
26 //检查DataTable是否包含此列(列名==对象的属性名)
27 if (dt.Columns.Contains(tempName))
28 {
29 // 判断此属性是否有Setter
30 if (!pi.CanWrite) continue;//该属性不可写,直接跳出
31 //取值
32 object value = dr[tempName];
33 //如果非空,则赋给对象的属性
34 if (value != DBNull.Value)
35 pi.SetValue(t, value, null);
36 }
37 }
38 //对象添加到泛型集合中
39 ts.Add(t);
40 }
41 return ts;
42 }
Public Shared Function convertToList(Of T As New)(dt As DataTable) As IList(Of T) Dim ts As List(Of T) = New List(Of T)() Dim type As Type = GetType(T) Dim tempName As String = String.Empty For Each dr As DataRow In dt.Rows Dim t As T = If((Nothing Is Nothing), Activator.CreateInstance(Of T)(), Nothing) Dim propertys As PropertyInfo() = t.[GetType]().GetProperties() Dim array As PropertyInfo() = propertys Dim i As Integer = 0 While i < array.Length Dim pi As PropertyInfo = array(i) tempName = pi.Name If dt.Columns.Contains(tempName) Then If pi.CanWrite Then Dim value As Object = dr(tempName) If value IsNot DBNull.Value Then pi.SetValue(t, value, Nothing) End If End If End If i += 1 Continue While End While ts.Add(t) Next Return ts End Function
软件转换的:
你安装一个SharpDeveloper吧,下载地址:
http://www.icsharpcode.net/OpenSource/SD/Download/
这样大神就没有机会让你不胜感激了。
这个软件可以让你将C#转为VB.NET语言。
授人以鱼不如授人以渔,真心感谢爱编程的大叔~~