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



本文转载:CSDN博客