c# 通過反射動態為物件賦值 通用方法
阿新 • • 發佈:2019-02-14
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集合 } } } } }