zoukankan      html  css  js  c++  java
  • c# 反射得到实体类的字段名称和值,DataTable转List<T>

    /// <summary>
    /// 反射得到实体类的字段名称和值
    /// var dict = GetProperties(model);
    /// </summary>
    /// <typeparam name="T">实体类</typeparam>
    /// <param name="t">实例化</param>
    /// <returns></returns>
    public static Dictionary<object, object> GetProperties<T>(T t)
    {
        var ret = new Dictionary<object, object>();
        if (t == null) { return null; }
        PropertyInfo[] properties = t.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);
        if (properties.Length <= 0) { return null; }
        foreach (PropertyInfo item in properties)
        {
            string name = item.Name;
            object value = item.GetValue(t, null);
            if (item.PropertyType.IsValueType || item.PropertyType.Name.StartsWith("String"))
            {
                ret.Add(name, value);
            }
        }
        return ret;
    }
    
    //通过反射获取实体类 字段名和字段值
    RBAC.Model.SY_ADMIN model = new RBAC.Model.SY_ADMIN();
    var dict = GetProperties(model);
    foreach (var item in dict)
    {
        str += string.Format("{0}-----{1}<br/>", item.Key, item.Value);
    }
            /*         
                IList<Model1> t1 = DataTableToList<Model1>(dt);         
             */
            /// <summary>
            /// DataTable利用泛型填充实体类
            /// </summary>
            /// <typeparam name="T">实体类</typeparam>
            /// <param name="table">dt</param>
            /// <returns></returns>
            public static IList<T> DataTableToList<T>(DataTable table)
            {
                IList<T> list = new List<T>();
                T t = default(T);
                PropertyInfo[] propertypes = null;
                string tempName = string.Empty;
                foreach (DataRow row in table.Rows)
                {
                    t = Activator.CreateInstance<T>();
                    propertypes = t.GetType().GetProperties();
                    foreach (PropertyInfo pro in propertypes)
                    {
                        tempName = pro.Name;
                        if (table.Columns.Contains(tempName))
                        {
                            object value = MSCL.Until.IsNullOrDBNull(row[tempName]) ? null : row[tempName];
                            pro.SetValue(t, value, null);
                        }
                    }
                    list.Add(t);
                }
                return list;
            }
  • 相关阅读:
    无约束优化算法——牛顿法与拟牛顿法(DFP,BFGS,LBFGS)
    撤销重做功能实现
    疯狂值班表(人员跟日期生成的视图)
    从零开始---控制台用c写俄罗斯方块游戏(2)
    unity3d关于碰撞问题
    主进程和服务进程通信调用Acrobat.AcroPDDoc时出现的问题
    echarts
    Wpf DataGrid动态添加列,行数据(二)
    Wpf DataGrid动态添加列,行数据(一)
    wpf学习资料链接(做记录)
  • 原文地址:https://www.cnblogs.com/smartsmile/p/7668456.html
Copyright © 2011-2022 走看看