public static List<T> HubbleTableToList<T>(this DataTable dt) where T:Class
{
List<T> _list = new List<T>();
if (dt == null) return _list;
T model;
foreach (DataRow dr in dt.Rows)//進行循環dataTable行數據
{
model = Activator.CreateInstance<T>();//獲取泛型類型的新實例
foreach (DataColumn dc in dr.Table.Columns)//循環該行的列
{
object drValue = dr[dc.ColumnName];//根據列名獲取行數據
PropertyInfo pi = model.GetType().GetProperty(dc.ColumnName);//model.GetType()表示獲取model的類型,GetProperty()獲取指定名稱的公共屬性,其中需要引用using System.Reflection;
if (pi != null && pi.CanWrite && (drValue != null && !Convert.IsDBNull(drValue)))
{
if (pi.PropertyType == typeof(int)||pi.PropertyType==typeof(int?))//注:如果未加此判斷,則會出現 類型“System.Int64”的對象無法轉換為類型“System.Int32”。的錯誤
{
drValue = Convert.ToInt32(drValue);
}
pi.SetValue(model, drValue, null);
}
}
_list.Add(model);
}
return _list;
}