[C#] 实体转换辅助类 →→→→→进入此内容的聊天室

来自 , 2020-06-04, 写在 C#, 查看 129 次.
URL http://www.code666.cn/view/978fce5b
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Data;
  5. using System.Reflection;
  6. namespace Tong.Framework
  7. {
  8.     /// <summary>    
  9.     /// 实体转换辅助类    
  10.     /// </summary>    
  11.     public class ModelConvertHelper<T> where T : new()
  12.     {
  13.         public static IList<T> ConvertToModel(DataTable dt)
  14.         {
  15.             // 定义集合    
  16.             IList<T> ts = new List<T>();
  17.             // 获得此模型的类型  
  18.             Type type = typeof(T);
  19.             string tempName = "";
  20.  
  21.             foreach (DataRow dr in dt.Rows)
  22.             {
  23.                 T t = new T();
  24.                 // 获得此模型的公共属性      
  25.                 PropertyInfo[] propertys = t.GetType().GetProperties();
  26.                 foreach (PropertyInfo pi in propertys)
  27.                 {
  28.                     tempName = pi.Name;  // 检查DataTable是否包含此列    
  29.  
  30.                     if (dt.Columns.Contains(tempName))
  31.                     {
  32.                         // 判断此属性是否有Setter      
  33.                         if (!pi.CanWrite) continue;
  34.  
  35.                         object value = dr[tempName];
  36.                         if (value != DBNull.Value)
  37.                             pi.SetValue(t, value, null);
  38.                     }
  39.                 }
  40.                 ts.Add(t);
  41.             }
  42.             return ts;
  43.         }
  44.     }
  45. }
  46.  

回复 "实体转换辅助类"

这儿你可以回复上面这条便签

captcha