SqlDataReader、DataGridView、および List の 3 つのパラメーターを使用できる関数を作成しようとしています。
SqlDataReader の内容を取得してオブジェクトのリストを作成し、これを DataGridView にバインドします。
別のスタックオーバーフローユーザーからのいくつかのポインタを使用して、次のことを思いつきました。
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」にキャストできません。
オブジェクトには何でも保存できるという印象を受けました。このキャストを実行できない理由について誰か教えてもらえますか?
ありがとう、
アンディ