查看了一些方法之后,做了一些总结,此方法适用于传进的参数是List<T>类型,
但事先并不知道T的类型,T可以是自定义类型。
public DataTable CreateDataTable(Object o)
{
DataTable dt = new DataTable();
//DataColumn yearColumn = new DataColumn("Year", System.Type.GetType("System.String"));
//DataColumn monthColumn = new DataColumn("Month", System.Type.GetType("System.String"));
//dt.Columns.AddRange(new DataColumn[] { yearColumn, monthColumn});
//foreach (DateModel date in dlist)
//{
// DataRow newRow = dt.NewRow();
// newRow["Year"] = date.year;
// newRow["Month"] = date.month;
// dt.Rows.Add(newRow);
//}
//Type testType = typeof(DateModel); Type testType = o.GetType();
Type t = o.GetType().GetGenericArguments()[];
//object genericList = CreateGeneric(typeof(List<>), o.GetType().GetGenericArguments()[0]);
//genericList.GetType().InvokeMember("Add", BindingFlags.Default | BindingFlags.InvokeMethod, null, genericList, new Object[] { o});
////Type testType = typeof(CreateDataTableUtil);
//Assembly assembly = testType.Assembly;
//string name = assembly.FullName;//name = "WindowsFormsApplication6, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" //Type[] typeList = assembly.GetTypes(); // 获取类型
// // 针对每个类型获取详细信息 PropertyInfo[] propertys = t.GetProperties(); foreach (PropertyInfo pro in propertys)
{
DataColumn dc = new DataColumn();
dc = dt.Columns.Add(pro.Name, System.Type.GetType(pro.PropertyType.FullName));
}
IEnumerable list = o as IEnumerable;
foreach (Object obj in list)
{
DataRow newRow = dt.NewRow();
for (int i = ; i < propertys.Count(); i++)
{
newRow[dt.Columns[i]] = obj.GetType().GetProperty(dt.Columns[i].ToString()).GetValue(obj);
} dt.Rows.Add(newRow);
}
return dt;
//}
//public static object CreateGeneric(Type generic, Type innerType, params object[] args)
//{
// Type specificType = generic.MakeGenericType(new System.Type[] { innerType });
// return Activator.CreateInstance(specificType, args);
}
}