Reputation: 1439
I went to an interview recently and there they asked me the following question:
Write a component to travel through an object hierarchy based on the data path passed in and return the value of the property implemeting the following method:
Public object getValueFromPath(object parentObj, string dataPath);
The object hierarchy will be some thing like this:
Object1
objectRef2
property1
property2
parentObj will be Object1
dataPath will be objectRef2.property2
Can some one give me an idea how I can do that.
Upvotes: 0
Views: 670
Reputation: 32586
You would need to use reflection.
First step would be to split the dataPath
on .
, and get a reference to the System.Type
object representing the type of parentObj
(parentObj.GetType()
).
Then for each element in the path you would use something like .GetMember(...)
on the Type
object to find the member with that name, and update the current Type
object accordingly.
Once you get to the property at the end, and you have the associated ProprtyInfo
object, you then need to call .GetValue(...)
to get the value of the property.
Upvotes: 5