I have a scenario where I have to get an array of strings that represent each of the property names used within a Func parameter. Here is an example implementation:
public class CustomClass<TSource>
{
public string[] GetPropertiesUsed
{
get
{
// do magical parsing based upon parameter passed into CustomMethod
}
}
public void CustomMethod(Func<TSource, object> method)
{
// do stuff
}
}
Here would be an example usage:
var customClass = new CustomClass<Person>();
customClass.CustomMethod(src => "(" + src.AreaCode + ") " + src.Phone);
...
var propertiesUsed = customClass.GetPropertiesUsed;
// propertiesUsed should contain ["AreaCode", "Phone"]
The part I’m stuck on in the above is the “do magical parsing based upon parameter passed into CustomMethod.”
You’ll need to change your CustomMethod to take an
Expression<Func<TSource, object>>, and probably subclass theExpressionVisitor, overridingVisitMember:This should get you started in the right direction. Let me know if you need some help figuring out the “… code here …” part.
Useful links: