標籤:datatable public 數組 system class rem typedef setvalue efi
轉換那塊怕忘記,留存一下
using System;using System.Collections.Generic;using System.Data;using System.Linq;using System.Reflection;using System.Text;namespace App.Util{ public class DtConvertListHelper<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中所有的資料行 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,Convert.ChangeType(value,pi.PropertyType), null); if (!pi.PropertyType.IsGenericType) { //非泛型 pi.SetValue(t, string.IsNullOrEmpty(value.ToString()) ? null : Convert.ChangeType(value, pi.PropertyType), null); } else { //泛型Nullable<> Type genericTypeDefinition = pi.PropertyType.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { pi.SetValue(t, string.IsNullOrEmpty(value.ToString()) ? null : Convert.ChangeType(value, Nullable.GetUnderlyingType(pi.PropertyType)), null); } } } } } //對象添加到泛型集合中 ts.Add(t); } return ts; } }}
錶轉List泛型數組