【发布时间】:2017-10-21 04:48:06
【问题描述】:
我得到了代码行标题中提到的异常
values[i] = Props[i].GetValue(item, null);
我不确定是什么原因造成的。任何帮助,将不胜感激。
public static DataTable ToDataTable<T>(List<T> items)
{
DataTable dataTable = new DataTable(typeof(T).Name);
PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo prop in Props)
{
var type = (prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>) ? Nullable.GetUnderlyingType(prop.PropertyType) : prop.PropertyType);
dataTable.Columns.Add(prop.Name, type);
}
foreach (T item in items)
{
var values = new object[Props.Length];
for (int i = 0; i < Props.Length; i++)
{
values[i] = Props[i].GetValue(item, null);
}
dataTable.Rows.Add(values);
}
return dataTable;
}
【问题讨论】:
-
你传入的是什么类型的数据?该方法似乎适用于我的测试。例如,这里有一个基本集合:dotnetfiddle.net/6RWBpz
-
为您找到了一篇相关文章,通过快速谷歌搜索您的主题行:stackoverflow.com/questions/32143085/…
-
数据是一个字符串列表。
-
动态类型只能是等于 T 的 1 个值。我认为您从 Props 将 dataTable 列循环和设置为多种类型是不正确的。但这是一个猜测。