I access property value from a class object at run-time using reflection in C#.
public bool GetValue(string fieldName, out object fieldValue)
{
// Get type of current record
Type curentRecordType = _currentObject.GetType();
PropertyInfo property = curentRecordType.GetProperty(fieldName);
if (property != null)
{
fieldValue = property.GetValue(_currentObject, null).ToString();
return true;
}
else
{
fieldValue = null;
return false;
}
}
I pass Property Name as parameter: fieldName to this method.
Now, I need to access a property value from the child object of above class at run-time.
Can anyone there please guide how can I access child object property value?
Since you want to be able to find objects on arbitrarily-nested child objects, you need a function that you can call recursively. This is complicated by the fact that you may have children that refer back to their parent, so you need to keep track of which objects you’ve seen before in your search.
If you know what child object your property is in you can just pass the path to it, like so:
Instead of calling it like
GetValue("foo", out val)you would call it likeGetValue("foo.bar", out val).