忘了出處 ,這個是轉別人的
public class DataToList<T> where T : new()
{
/// <summary>
/// 利用反射和泛型
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
public static List<T> ConvertToList(DataTable dt)
{
// 定義集合
List<T> ts = new List<T>();
// 獲得此模型的類型
Type type = typeof(T);
//定義一個臨時變量
string tempName = string.Empty;
//遍歷DataTable中所有的數據行
if (dt != null)
{
foreach (DataRow dr in dt.Rows)
{
T t = new T();
// 獲得此模型的公共屬性
PropertyInfo[] propertys = t.GetType().GetProperties();
//遍歷該對象的所有屬性
foreach (PropertyInfo pi in propertys)
{
tempName = pi.Name;//將屬性名稱賦值給臨時變量
//檢查DataTable是否包含此列(列名==對象的屬性名)
if (dt.Columns.Contains(tempName))
{
// 判斷此屬性是否有Setter
if (!pi.CanWrite) continue;//該屬性不可寫,直接跳出
//取值
object value = dr[tempName];
//如果非空,則賦給對象的屬性
if (value != DBNull.Value)
pi.SetValue(t, value, null);
}
}
//對象添加到泛型集合中
ts.Add(t);
}
}
return ts;
}
}