zoukankan      html  css  js  c++  java
  • DataSet结果转模型类

    引入命名空间:

    using System.Data;
    using System.Reflection;

    类封装代码:

        public class ModelHelper
        {
            public T To<T>(DataRow dr) where T : new()
            {
                T model= new T();                   //T model = default(T); //model = Activator.CreateInstance<T>();
                Type t = model.GetType();                       //获取模型类的类型
    
                //循环遍历模型类的每一个属性,并为其赋值
                foreach (PropertyInfo pi in t.GetProperties())
                {
                    if (dr.Table.Columns.Contains(pi.Name))           //如果DataTable的列中包含当前的属性名
                    {
                        if (!pi.CanWrite) continue;
                        object value = dr[pi.Name];
                        if (value != DBNull.Value)
                        {
                            pi.SetValue(model, value, null);
                        }
                        else
                        {
                            pi.SetValue(model, null, null);
                        }
                    }
    
                }
    
                return model;
            }
    
            public IList<T> ToList<T>(DataTable dt) where T : new()
            {
                List<T> list = new List<T>();
                foreach (DataRow dr in dt.Rows)
                {
                    list.Add(To<T>(dr));
                }
                return list;
            }
    
    
            //另一种写法
            //public T To<T>(DataTable dt) where T : new()
            //{
            //    T model = default(T);
            //    model = Activator.CreateInstance<T>();
    
            //    PropertyInfo[] propertys = model.GetType().GetProperties();         //获取模型类的类型
    
            //    //循环遍历模型类的每一个属性,并为其赋值
            //    foreach (PropertyInfo pi in propertys)
            //    {
            //        if (dt.Columns.Contains(pi.Name))           //如果DataTable的列中包含当前的属性名
            //        {
            //            if (!pi.CanWrite) continue;
            //            object value = dt.Rows[0][pi.Name];
            //            if (value != DBNull.Value)
            //            {
            //                pi.SetValue(model, value, null);
            //            }
            //            else
            //            {
            //                pi.SetValue(model, null, null);
            //            }
            //        }
            //    }
    
            //    return model;
            //}
        }
  • 相关阅读:
    用命令行执行ROBOT FRAMEWORK
    RF ---library
    RF--- selenium
    RIDE指定log和report的输出目录
    robotframework运行时后台报错UnicodeDecodeError
    rf-demos (request)
    RobotFramework --RIDE介绍
    基于RFS(robot framework selenium)框架模拟POST/GET请求执行自动化接口测试
    volatile非原子性示例
    wait()方法写在while循环中可以在线程接到通知后再一次判断条件
  • 原文地址:https://www.cnblogs.com/zhangchaoran/p/8513430.html
Copyright © 2011-2022 走看看