2019.8.14 更新

补全了DataTable转泛型集合的方法:

/// <summary>
/// DataTable转实体类集合
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dt">DataTable数据集</param>
public static List<T> SetValueForListByData<T>(DataTable dt) where T : new()
{
  List<T> List = new List<T>();
  foreach (DataRow dr in dt.Rows)
  {
    T Entity = new T();

    //这里是昨天就发在随笔里的方法,下翻就能看到,
    SetValueForEntityByData(Entity, dr);

    //下面一段是完整的赋值流程,与上面调用的方法二取一即可。
    //PropertyInfo[] propertyInfo = Entity.GetType().GetProperties();
    //Type type = Entity.GetType();
    //foreach (PropertyInfo item in propertyInfo)
    //{
      // item.SetValue(Entity, Convert.ChangeType(dr[item.Name], item.PropertyType));
    //}
    List.Add(Entity);
  }
  return List;
}

在循环DataTable中的每一行时调用该方法,可避免实体类属性众多时手动赋值的麻烦。

1.有返回值版本,该版本需要注意的是,普通情况下的泛型没有构造器,无法直接通过new关键字实例化,所以需要在方法签名后面加上 where T : new(),为方法内的所有泛型变量添加一个空构造器,使之可以实例化。它最终的效果是实例化实体类并且赋值,然后return赋值结果。

public static T SetValueForEntityByData<T>(DataRow dr) where T : new()
{
  T Entity = new T();
  PropertyInfo[] propertyInfo = Entity.GetType().GetProperties();
  Type type = Entity.GetType();
  foreach (PropertyInfo item in propertyInfo)
  {
    item.SetValue(Entity, Convert.ChangeType(dr[item.Name], item.PropertyType));
  }
  return Entity;
}

2.无返回值版本,不用担心泛型的实例化,省略where,但是需要能理解引用类型与值类型在内存上的储存方式的区别。它最终的效果是为传入的实体类赋值,并且赋值结果不用经过return便可以体现。

public static void SetValueForEntityByData<T>(T Entity,DataRow dr)
{
  Type type = typeof(T);
  PropertyInfo[] propertyInfo = Entity.GetType().GetProperties();
  foreach (PropertyInfo item in propertyInfo)
  {
    item.SetValue(Entity, Convert.ChangeType(dr[item.Name], item.PropertyType));
  }
}

最新文章

  1. 挑子学习笔记:特征选择——基于假设检验的Filter方法
  2. Markdown基本语法
  3. Makefile笔记之一 ------ 变量的引用及赋值
  4. [转]非常实用的15款开源PHP类库
  5. Linux &amp; Oracle 安装目录说明
  6. php课程---建立一个简单的下拉列表框
  7. Oracle 10g ORA-01034: ORACLE not available 错误
  8. 添加Pods后,import无提示的解决办法
  9. 安装orcle10g oel5.6
  10. Hadoop-1.1.2、HBase-0.94.7完全分布式集群结构
  11. 国内ng学习网站
  12. 【java图形计算器】 java awt swing组件应用
  13. 【Beta】 第六次Daily Scrum Meeting
  14. ASP.NET部分代码示例
  15. [manjaro]换源到中国并按照速度排序
  16. Clustering[Introduction]
  17. 【转】fiddler抓包HTTPS请求
  18. js高级---本地对象、内置对象、宿主对象
  19. IO流中File文件最常用和直接的用法
  20. python标准库介绍——27 random 模块详解

热门文章

  1. Python基础:12函数细节
  2. WebLogic Server再曝高风险远程命令执行0day漏洞,阿里云WAF支持免费应急服务
  3. 14-1 jquery的dom操作和事件对象
  4. H3C 常用设备管理命令
  5. MyBatis-使用XML或注解的简单实例
  6. 使用php函数ini_set()重新设置某个配置的设置值
  7. JavaScript跨域问题
  8. 2019-9-9-dotnet-获取本机-IP-地址方法
  9. Python--day65--模板语言之filter
  10. 解析XML内容到User对象