我有一个转换List<T>
为DataTable
使用反射的方法。我想通过传递多个列表来利用该方法创建 DataSet,其中每个列表可能包含不同类型的对象。
下面是给我编译时错误的代码:
“ The type arguments for method 'ExportToExcel.CreateExcelFile.ListToDataTable<T>(System.Collections.Generic.List<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly
.” - 在行“ var dt = Util.ListToDataTable(item);
”
public static class Util
{
public static DataSet GetDataSet(List<string> title, List<IList> data)
{
DataSet ds = new DataSet();
int idx= 0;
foreach (var item in data)
{
//here I get compile time error "The type arguments for method
// 'ExportToExcel.CreateExcelFile.ListToDataTable<T>
// (System.Collections.Generic.List<T>)' cannot be inferred from the usage.
// Try specifying the type arguments explicitly. "
var dt = Util.ListToDataTable(item);
if (title.Count >= idx)
{
dt.TableName = title[idx];
}
idx++;
ds.Tables.Add(dt);
}
return ds;
}
public static System.Data.DataTable ListToDataTable<T>(List<T> list)
{
var dt = new System.Data.DataTable();
foreach (PropertyInfo info in typeof(T).GetProperties())
{
dt.Columns.Add(new DataColumn(info.Name, info.PropertyType));
}
foreach (T t in list)
{
DataRow row = dt.NewRow();
foreach (PropertyInfo info in typeof(T).GetProperties())
{
row[info.Name] = info.GetValue(t, null);
}
dt.Rows.Add(row);
}
return dt;
}
}
这是我的调用 testMethod
[TestMethod]
public void TestDataSetGeneration_WithMultipleLists()
{
IList list = new List<User>();
list.Add(new User(){FirstName = "Mahesh", LastName = "Chaudhari", IsExternal = true, UpdatedOn = DateTime.Now});
list.Add(new User(){FirstName = "Mahesh1",LastName = "Chaudhari1",IsExternal = true,UpdatedOn = DateTime.Now});
list.Add(new User(){FirstName = "Mahesh2",LastName = "Chaudhari2",IsExternal = false,UpdatedOn = DateTime.Now});
IList hcps = new List<HCPUser>() { new HCPUser(){FirstName = "HCP1",LastName = "HCP1"}};
var lists = new List<IList>();
lists.Add(list);
lists.Add(hcps);
var titles = new List<String> { "Users", "HCPs"};
var result = Util.GetDataSet(titles ,lists );
Assert.IsTrue(result != null);
}
我认为 Util.ListToDataTable 方法需要特定类型,它只在运行时获得。在这种情况下,我将如何调用此方法?