本案例提供了:把DataRow轉換為單個實體、dataTable轉換為List泛型支援時間格式轉換。
下文的方法都是擴充方法。擴充方法要求寫在靜態類中,方法也要靜態。
它必須在一個非嵌套、非泛型的靜態類中
它至少要有一個參數
第一個參數必須加上this關鍵字作為首碼(第一個參數類型也稱為擴展類型,即指方法對這個類型進行擴展)
第一個參數不能用其他任何修飾符(如不能使用ref out等修飾符)
第一個參數的類型不能是指標類型
1.將DataRow轉換為實體
/// <summary>
/// DataRow擴充方法:將DataRow類型轉化為指定類型的實體
/// </summary>
/// <typeparam name="T">實體類型</typeparam>
/// <returns></returns>
public static T ToModel<T>(this DataRow dr) where T : class,new()
{
return ToModel<T>(dr,true);
}
2.將DataRow轉換為實體可設置時間格式轉換
/// <summary>
/// DataRow擴充方法:將DataRow類型轉化為指定類型的實體
/// </summary>
/// <typeparam name="T">實體類型</typeparam>
/// <param name="dateTimeToString">是否需要將日期轉換為字串,預設為轉換,值為true</param>
/// <returns></returns>
/// <summary>
public static T ToModel<T>(this DataRow dr, bool dateTimeToString) where T : class, new()
{
if (dr != null)
return ToList<T>(dr.Table, dateTimeToString).First();
return null;
}
3.將DataTable轉換為實體
/// <summary>
/// DataTable擴充方法:將DataTable類型轉化為指定類型的實體集合
/// </summary>
/// <typeparam name="T">實體類型</typeparam>
/// <param name="dateTimeToString">是否需要將日期轉換為字串,預設為轉換,值為true</param>
/// <returns></returns>
public static List<T> ToList<T>(this DataTable dt, bool dateTimeToString) where T : class, new()
{
List<T> list = new List<T>();
if (dt != null)
{
List<PropertyInfo> infos = new List<PropertyInfo>();
Array.ForEach<PropertyInfo>(typeof(T).GetProperties(), p =>
{
if (dt.Columns.Contains(p.Name) == true)
{
infos.Add(p);
}
});//獲取類型的屬性集合
SetList<T>(list, infos, dt, dateTimeToString);
}
return list;
}
4.轉換實現代碼
private static void SetList<T>(List<T> list, List<PropertyInfo> infos, DataTable dt, bool dateTimeToString) where T : class, new()
{
foreach (DataRow dr in dt.Rows)
{
T model = new T();
infos.ForEach(p =>
{
if (dr[p.Name] != DBNull.Value)//判斷屬性在不為空
{
object tempValue = dr[p.Name];
if (dr[p.Name].GetType() == typeof(DateTime) && dateTimeToString == true)//判斷是否為時間
{
tempValue = dr[p.Name].ToString();
}
try
{
p.SetValue(model, tempValue, null);//設置
}
catch { }
}
});
list.Add(model);
}//結束循
留言列表