How can I get property name strings used in Func of T

I have a scenario where I need to get an array of strings that are the property names used in the 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 is a usage example:

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 with in the above is "do magic parsing based on the parameter passed to CustomMethod."

+3
source share
2 answers

You will need to modify your CustomMethod to take Expression<Func<TSource, object>>and, possibly, a subclass ExpressionVisitor, overriding VisitMember:

public void CustomMethod(Expression<Func<TSource, object>> method)
{
     PropertyFinder lister = new PropertyFinder();
     properties = lister.Parse((Expression) expr);
}

// this will be what you want to return from GetPropertiesUsed
List<string> properties;

public class PropertyFinder : ExpressionVisitor
{
    public List<string> Parse(Expression expression)
    {
        properties.Clear();
        Visit(expression);
        return properties;
    }

    List<string> properties = new List<string>();

    protected override Expression VisitMember(MemberExpression m)
    {
        // look at m to see what the property name is and add it to properties
        ... code here ...
        // then return the result of ExpressionVisitor.VisitMember
        return base.VisitMember(m);
    }
}

This should help you get started in the right direction. Let me know if you need help figuring out the "... code here ..." part.

Useful links:

+6

Expression<Func<>>. , ( func). , , - . .

+10

Source: https://habr.com/ru/post/1786185/


All Articles