如何获取F的Func中使用的属性名称字符串

Jes*_*ule 3 c# parameters lambda

我有一个场景,我必须得到一个字符串数组,表示Func参数中使用的每个属性名称.这是一个示例实现:

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
  }
}
Run Code Online (Sandbox Code Playgroud)

这是一个示例用法:

var customClass = new CustomClass<Person>();
customClass.CustomMethod(src => "(" + src.AreaCode + ") " + src.Phone);

...

var propertiesUsed = customClass.GetPropertiesUsed;
// propertiesUsed should contain ["AreaCode", "Phone"]
Run Code Online (Sandbox Code Playgroud)

我在上面坚持的部分是"根据传递给CustomMethod的参数进行魔法解析".

luc*_*uke 10

你应该使用Expression<Func<>>类来代替.表达式包含实际的树,并且可以很容易地被编译以获得委托(这是一个func).你真正想做的是看表达的主体和理由.Expression类为您提供所有必要的基础结构.


Mar*_*iec 6

你需要改变你的CustomMethod来取代Expression<Func<TSource, object>>,并且可能是子类ExpressionVisitor,覆盖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);
    }
}
Run Code Online (Sandbox Code Playgroud)

这应该让你开始朝着正确的方向前进.如果您需要帮助找出"......代码......"部分,请告诉我.

有用的链接: