I\'m currently setting all of the values of my class object Record
.
This is the code that I\'m using to populate the record at the moment, property by p
Yes, you could make an indexer on your Record class that maps from the property name to the correct property. This would keep all the binding from property name to property in one place eg:
public class Record
{
public string ItemType { get; set; }
public string this[string propertyName]
{
set
{
switch (propertyName)
{
case "itemType":
ItemType = value;
break;
// etc
}
}
}
}
Alternatively, as others have mentioned, use reflection.
I tried what Samuel Slade has suggested. Didn't work for me. The PropertyInfo
list was coming as empty. So, I tried the following and it worked for me.
Type type = typeof(Record);
FieldInfo[] properties = type.GetFields();
foreach (FieldInfo property in properties) {
Debug.LogError(property.Name);
}
You could possibly use Reflection to do this. As far as I understand it, you could enumerate the properties of your class and set the values. You would have to try this out and make sure you understand the order of the properties though. Refer to this MSDN Documentation for more information on this approach.
For a hint, you could possibly do something like:
Record record = new Record();
PropertyInfo[] properties = typeof(Record).GetProperties();
foreach (PropertyInfo property in properties)
{
property.SetValue(record, value);
}
Where value
is the value you're wanting to write in (so from your resultItems
array).
// the index of each item in fieldNames must correspond to
// the correct index in resultItems
var fieldnames = new []{"itemtype", "etc etc "};
for (int e = 0; e < fieldNames.Length - 1; e++)
{
newRecord
.GetType()
.GetProperty(fieldNames[e])
.SetValue(newRecord, resultItems[e]);
}