利用委托反射将DataTable转换为实体集

类泛型的约束:

1 public static class ToModel<T> where T : class, new()

定义委托:

1 public delegate void SetString(string value);

创建委托方法:

1 private static SetString CreateStringDelegate(T model, string propertyName)

2 {

3    MethodInfo mi = model.GetType().GetProperty(propertyName).GetSetMethod();

4    Type type = typeof(SetString);

5    return Delegate.CreateDelegate(type, model, mi) as SetString;

6  }

利用反射和委托将DataTable转换为实体集:

 1         public static IList<T> GetDelegate_ToModelList(DataTable dt)

 2         {

 3             IList<T> list = new List<T>();

 4             if (dt == null || dt.Rows.Count < 1) return list;

 5             SetString setDelegateString;

 6             foreach (DataRow dr in dt.Rows)

 7             {

 8                 T model = new T();

 9                 foreach (DataColumn dc in dt.Columns)

10                 {

11                     setDelegateString = CreateStringDelegate(model, dc.ColumnName);

12                     setDelegateString(dr[dc.ColumnName].ToString());

13                 }

14                 list.Add(model);

15             }

16             return list;

17         }

这样写问题就来了,因为委托定义的参数时string类型的,因为我们实体中可能有int或者DateTime类型的,这时就需要用上泛型委托了

如果这样定义委托:

1 public delegate void SetString<PT>(PT value)

创建委托方法(这里有问题,不知如何处理):

1         private static SetString CreateStringDelegate(T model, string propertyName)

2         {

3             MethodInfo mi = model.GetType().GetProperty(propertyName).GetSetMethod();

4             Type type = typeof(model).GetProperty(propertyName).PropertyType;

5             return Delegate.CreateDelegate(type, model, mi) as SetString<type>;

6         }

利用反射和委托将DataTable转换为实体集:

 1         public static IList<T> GetDelegate_ToModelList(DataTable dt)

 2         {

 3             IList<T> list = new List<T>();

 4             if (dt == null || dt.Rows.Count < 1) return list;

 5             foreach (DataRow dr in dt.Rows)

 6             {

 7                 T model = new T();

 8                 foreach (DataColumn dc in dt.Columns)

 9                 {

10                     SetString<typeof(T).GetProperty(dc.ColumnName).PropertyType> setDelegateString = CreateStringDelegate(model, dc.ColumnName);

11                     setDelegateString(dr[dc.ColumnName].ToString());

12                 }

13                 list.Add(model);

14             }

15             return list;

16         }

一直疑惑着,希望有人帮我解决疑惑,直接反射的方法我也有,但是这个问题不解决,心里一直有疙瘩,希望有人帮帮忙,谢谢!

你可能感兴趣的:(Datatable)