zoukankan      html  css  js  c++  java
  • 泛型的运用(用于查询数据后DataTable转实体类)

    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));
      }
    }

  • 相关阅读:
    centos 7:network: 正在打开接口 ens33: 错误:激活连接失败:No suitable device found for this connection.
    python 连接 hive 的 HiveServer2 的配置坑
    node的 node-sass@^4.11.0 出现:npm: no such file or directory, scandir '.../node_modules/node-sass/vendor'
    DX关联VS
    PIX
    英特尔® 图形性能分析器(Intel® GPA)
    C++之异常处理
    VS挂接崩溃包
    system 函数
    C++ Template
  • 原文地址:https://www.cnblogs.com/FavoriteMango/p/11346413.html
Copyright © 2011-2022 走看看