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




  • 相关阅读:
    新站发布——寻爱交友网
    博客园居然还在运营
    关于Method类的invoke方法
    创建对象的四种方法
    事务操作
    数据库的并发
    run( )和start( )方法
    JAVA语言的下面几种数组复制方法中,哪个效率最高?
    构造函数问题
    上下转型的调用问题
  • 原文地址:https://www.cnblogs.com/smartsmile/p/6234049.html
Copyright © 2020-2023  润新知