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

时间:2011-01-18 16:40:43

标签: 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
  }
}

以下是一个示例用法:

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

...

var propertiesUsed = customClass.GetPropertiesUsed;
// propertiesUsed should contain ["AreaCode", "Phone"]

上面我坚持的部分是“基于传递给CustomMethod的参数进行神奇的解析。”

2 个答案:

答案 0 :(得分:10)

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

答案 1 :(得分:6)

您需要更改自定义方法以获取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);
    }
}

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

有用的链接:

相关问题