Given a string: "Person.Address.Postcode" I want to be able to get/set this postcode property on an instance of Person. How can I do this? My idea was to split the string by "." and then iterate over the parts, looking for the property on the previous type, then build up an expression tree that would look something like (apologies for the pseudo syntax):
(person => person.Address) address => address.Postcode
I'm having real trouble acutally creating the expression tree though! If this is the best way, can someone suggest how to go about it, or is there an easier alternative?
Thanks
Andrew
public class Person
{
public int Age { get; set; }
public string Name { get; set; }
public Address Address{ get; set; }
public Person()
{
Address = new Address();
}
}
public class Address
{
public string Postcode { get; set; }
}
Why you don't use recursion? Something like:
You want to look at providing your own PropertyDescriptor's via TypeConverter or some other source.
I have implemented exactly what you describe for current project (sorry, commercial, else I would share), by deriving from BindingSource, and providing the information via there.
The idea is as follows:
All you need to do is, once you have the type is to create little 'stacks' for the getter and setters of properties, and those you can collect via walking the property tree of the type and its properties breadth first, limiting the depths to a specified number of levels and removing circular references depending on your data structures.
I am using this quite successfully with Linq2SQL objects and in combination with their binding lists :)
It sounds like you're sorted with regular reflection, but for info, the code to build an expression for nested properties would be very similar to this order-by code.
Note that to set a value, you need to use
GetSetMethod()
on the property and invoke that - there is no inbuilt expression for assigning values after construction (although it is supported in 4.0).(edit) like so:
If anyone is interested in the performance trade-off between the simple reflection approach (also nice examples here and here) and Marc's Expression-building approach...
My test involved getting a relatively deep property (A.B.C.D.E) 10,000 times.
Obviously this is a very specific test, and I haven't considered optimisations or setting properties, but I think a 26x performance hit is worth noting.
Expression Tree