المساعد الشخصي الرقمي

مشاهدة النسخة كاملة : Create an object with a string.



C# Programming
05-12-2012, 10:03 AM
I am converting from PHP to C# and I might be doing this completely wrong but here goes. I am reading rows from a database with a reader. Then using a foreach command I am walking through the records creating an object and then adding the object to a List. I then return the list to be used for other purposes. But since the object that I am adding to the List is sent by reference it ends up filling the list with the values of the last object added. I am looking for advice on alternate was to fill the List or alternate ways to use the objects. Please try to refrain from just telling me I am and idiot. Be assured I am already aware of this fact.http://www.barakasoft.com/script/Forums/Images/smiley_smile.gif Thanks to anyone that can offer advice. Below is some of the code. I hope that I posted it OK.

Mark

public object find_by_sql(string sql_statement, Type object_type, database working_database) { //Using the supplied sql statement query the database and return a reader object. working_database.reader = (SqlDataReader)working_database.query(sql_statement); //Instantiate a object determined by the calling class using the argument object_type object defined_object = Activator.CreateInstance(object_type); //Tnstantiate an Array of objects to return. List object_array = new List(); //Step through the returned data rows from the sql statement while (working_database.reader.Read()) { Console.WriteLine("Calling Instantiation"); object_array.Add(instantiate(working_database.reader, defined_object)); Console.WriteLine("object test = " + defined_object.GetType().GetField("descr").GetValue(defined_object).ToString()); Console.WriteLine("Returned from Instantiation"); } return (object_array); } private static object instantiate(SqlDataReader records,object defined_object) { for (int i = 0; i < (records.FieldCount); i++) { int one = (int)records.GetInt32(0); string two = (string)records.GetName(i); var three = records[i]; //record_values.Add(two, three); Console.WriteLine("{0} : {1} - {2}", one, two, three); defined_object.GetType().GetField(two).SetValue(defined_object, three); //Console.WriteLine("{0}, {1}", working_database.reader.GetInt32(0), String.Format("{0}", working_database.reader[4])); //return_value = instantiate(working_database.reader); } return(defined_object); }