【发布时间】:2012-06-11 19:24:33
【问题描述】:
我正在尝试编写一个可以接受三个参数的函数:SqlDataReader、DataGridView 和 List。
我想获取 SqlDataReader 的内容并创建一个对象列表,然后将其绑定到 DataGridView。
根据另一个 Stack Overflow 用户的一些建议,我得出以下结论:
public void FillArrayList<T>(DataGridView grid, SqlDataReader reader, List<T> list)
{
//Fill the list with the contents of the reader
while (reader.Read())
{
Object obj = new Object();
Type type = typeof(T);
FieldInfo[] fields = type.GetFields(); // Get the fields of the assembly
int i = 0;
foreach(var field in fields)
{
field.SetValue(obj, reader[i]); // set the fields of T to the reader's value
i++;
}
list.Add((T)obj);
}
grid.DataSource = list;
}
运行代码时,将对象转换为类型 T 时出现错误:
无法将“System.Object”类型的对象转换为类型 'TestHarness.Organisation'。
我的印象是 Object 可以存储任何东西。谁能告诉我为什么无法执行此演员表?
谢谢,
安迪
【问题讨论】:
-
检查这可能会对您有所帮助。 [stackoverflow.com/questions/5174537/…[1]:stackoverflow.com/questions/5174537/…
标签: c# list object datagridview sqldatareader