我怎样才能在T的Func键使用属性名的字符串 [英] How can I get property name strings used in a Func of T

查看:92
本文介绍了我怎样才能在T的Func键使用属性名的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一种情况,我一定要得到代表每个函数求参数中使用的属性名称的字符串数组。下面是一个例子实现:

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"]



部分我M在上面停留在是的做基于传入CustomMethod参数神奇的解析。

推荐答案

您将需要更改CustomMethod采取一种表达式来; Func键< TSource,对象>> ,也许继承了 ExpressionVisitor ,覆盖 VisitMember

You'll need to change your CustomMethod to take an Expression<Func<TSource, object>>, and probably subclass the 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 get you started in the right direction. Let me know if you need some help figuring out the "... code here ..." part.

相关链接:

  • Expression Trees
  • How to Modify Expression Trees
  • ExpressionVisitor
  • VisitMember
  • MemberExpression

这篇关于我怎样才能在T的Func键使用属性名的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆