SQLステートメント(文字列)を受け取り、結果を組織のコレクションであるArrayList(organisationList)にロードする次のコードがあります。
public void FillDataGridView(DataGridView grid, string SQLCommand)
{
SqlCommand dataCommand = new SqlCommand();
dataCommand.Connection = dataConnection;
dataCommand.CommandType = CommandType.Text;
dataCommand.CommandText = SQLCommand;
SqlDataReader dataReader = dataCommand.ExecuteReader();
while (dataReader.Read())
{
Organisation org = new Organisation();
org.OrganisationId = (int)dataReader["OrganisationId"];
org.OrganisationName = (string)dataReader["OrganisationName"];
organisationList.Add(org);
}
grid.DataSource = organisationList;
dataReader.Close();
}
渡されたArrayListを埋められるように、このメソッドを適応させたいと思います。
リストをメソッドに渡して、次のようなものにすることは可能ですか?
public void FillArrayList(DataGridView grid, SqlDataReader reader, ArrayList list)
{
//Fill the list with the contents of the reader
while (reader.Read())
{
Object obj = new Object
for(int i; i = 0; i < obj.NoOfProperties)
{
obj.Property[i] = reader[i];
}
list.Add(obj);
}
}
これが少し曖昧な場合は申し訳ありませんが、私はOOPにまったく慣れておらず、少し迷っています。
編集:Darren Daviesのアドバイスに基づいて、メソッドを次のように変更しました。
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
// field.setValue(obj, reader[field.Name]); // You can also set the field value to the explicit reader name, i.e. reader["YourProperty"]
i++;
}
list.Add((T)obj);
}
grid.DataSource = list;
}
コードを実行すると、オブジェクトをタイプTにキャストするときにエラーが発生します。
タイプ「System.Object」のオブジェクトをタイプ「TestHarness.Organisation」にキャストできません。
オブジェクトは何でも保存できるという印象を受けました。このキャストが実行できない理由について誰かにアドバイスしてもらえますか?
ありがとう、
アンディ