查看了一些方法之后,做了一些总结,此方法适用于传进的参数是List<T>类型,
但事先并不知道T的类型,T可以是自定义类型。
1 public DataTable CreateDataTable(Object o) 2 { 3 DataTable dt = new DataTable(); 4 //DataColumn yearColumn = new DataColumn("Year", System.Type.GetType("System.String")); 5 //DataColumn monthColumn = new DataColumn("Month", System.Type.GetType("System.String")); 6 //dt.Columns.AddRange(new DataColumn[] { yearColumn, monthColumn}); 7 //foreach (DateModel date in dlist) 8 //{ 9 // DataRow newRow = dt.NewRow(); 10 // newRow["Year"] = date.year; 11 // newRow["Month"] = date.month; 12 // dt.Rows.Add(newRow); 13 //} 14 //Type testType = typeof(DateModel); 15 16 Type testType = o.GetType(); 17 Type t = o.GetType().GetGenericArguments()[0]; 18 //object genericList = CreateGeneric(typeof(List<>), o.GetType().GetGenericArguments()[0]); 19 //genericList.GetType().InvokeMember("Add", BindingFlags.Default | BindingFlags.InvokeMethod, null, genericList, new Object[] { o}); 20 ////Type testType = typeof(CreateDataTableUtil); 21 //Assembly assembly = testType.Assembly; 22 //string name = assembly.FullName;//name = "WindowsFormsApplication6, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" 23 24 //Type[] typeList = assembly.GetTypes(); // 获取类型 25 // // 针对每个类型获取详细信息 26 27 PropertyInfo[] propertys = t.GetProperties(); 28 29 foreach (PropertyInfo pro in propertys) 30 { 31 DataColumn dc = new DataColumn(); 32 dc = dt.Columns.Add(pro.Name, System.Type.GetType(pro.PropertyType.FullName)); 33 } 34 IEnumerable list = o as IEnumerable; 35 foreach (Object obj in list) 36 { 37 DataRow newRow = dt.NewRow(); 38 for (int i = 0; i < propertys.Count(); i++) 39 { 40 newRow[dt.Columns[i]] = obj.GetType().GetProperty(dt.Columns[i].ToString()).GetValue(obj); 41 } 42 43 dt.Rows.Add(newRow); 44 } 45 return dt; 46 //} 47 //public static object CreateGeneric(Type generic, Type innerType, params object[] args) 48 //{ 49 // Type specificType = generic.MakeGenericType(new System.Type[] { innerType }); 50 // return Activator.CreateInstance(specificType, args); 51 } 52 }