c# 通过反射动态为对象赋值 通用方法

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Reflection;

namespace BLL
{
    /// <summary>
    /// 利用反射动态为对象赋值
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class GenericList<T> : List<T>
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="dt">数据源</param>
        /// <param name="classPath">实体类型路径</param>
        public GenericList(DataTable dt, string classPath)
        {
            System.Type type = System.Type.GetType(classPath);//获取指定名称的类型
            object instance = Activator.CreateInstance(type, null);//创建指定类型实例
            PropertyInfo[] fields = instance.GetType().GetProperties();//获取指定对象的所有公共属性
            foreach (DataRow dr in dt.Rows)
            {
                object obj = Activator.CreateInstance(type, null);
                foreach (DataColumn dc in dt.Columns)
                {
                    foreach (PropertyInfo item in fields)
                    {
                        if (dc.ColumnName == item.Name)
                        {
                            if (dr[dc.ColumnName] != DBNull.Value)
                            {
                                object value;

                                value = Convert.ChangeType(dr[dc.ColumnName], (Nullable.GetUnderlyingType(item.PropertyType) ?? item.PropertyType));
                                //value = dr[dc.ColumnName];

                                item.SetValue(obj, value, null);//给对象赋值
                            }

                            continue;
                        }
                    }
                }
                this.Add((T)obj);//将对象填充到list集合
            }
        }
    }
}
}


猜你喜欢

转载自blog.csdn.net/hc1qq/article/details/80567869