Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I'm legitimately curious at how you would load the values of a class without using reflection unless you had methods hardcoded to accomplish it. I'm sure there's another answer, but I'm not too ashamed to say I do not have experience in it. As for something I wrote to auto-load data, I have two base data classes I work from: a single object and then a list. In the single object (BaseDataClass), I have this method.</p> <pre><code> public virtual void InitializeClass(DataRow dr) { Type type = this.GetType(); PropertyInfo[] propInfos = type.GetProperties(); for (int i = 0; i &lt; dr.ItemArray.GetLength(0); i++) { if (dr[i].GetType() != typeof(DBNull)) { string field = dr.Table.Columns[i].ColumnName; foreach (PropertyInfo propInfo in propInfos) { if (field.ToLower() == propInfo.Name.ToLower()) { // get data value, set property, break object o = dr[i]; propInfo.SetValue(this, o, null); break; } } } } } </code></pre> <p>And then in the data list </p> <pre><code>public abstract class GenericDataList&lt;T&gt; : List&lt;T&gt; where T : BaseDataClass { protected void InitializeList(string sql) { DataHandler dh = new DataHandler(); // my general database class DataTable dt = dh.RetrieveData(sql); if (dt != null) { this.InitializeList(dt); dt.Dispose(); } dt = null; dh = null; } protected void InitializeList(DataTable dt) { if (dt != null) { Type type = typeof(T); MethodInfo methodInfo = type.GetMethod("InitializeClass"); foreach (DataRow dr in dt.Rows) { T t = Activator.CreateInstance&lt;T&gt;(); if (methodInfo != null) { object[] paramArray = new object[1]; paramArray[0] = dr; methodInfo.Invoke(t, paramArray); } this.Add(t); } } } } </code></pre> <p>I'm open to criticism, because no one has ever reviewed this code before. I am the sole programmer where I work, so I do not have others to bounce ideas off of. Thankfully, now I've come across this website!</p> <p>Edit: You know what? Looking at it now, I don't see why I shouldn't just rewrite that last method as </p> <pre><code> protected void InitializeList(DataTable dt) { if (dt != null) { Type type = typeof(T); foreach (DataRow dr in dt.Rows) { T t = Activator.CreateInstance&lt;T&gt;(); (t as BaseDataClass).InitializeClass(dr); this.Add(t); } } } </code></pre> <p>I assume that works, although I haven't tested it. No need to use reflection on that part.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload