码迷,mamicode.com
首页 > 其他好文 > 详细

Traverse an expression tree and extract parameters

时间:2019-09-24 19:21:37      阅读:119      评论:0      收藏:0      [点我收藏+]

标签:sed   fun   ons   further   base   bsp   ado   nbsp   this   

Traverse an expression tree and extract parameters

 

I think as you‘ve said that using ExpressionVisitor works out to be a good approach. You don‘t need to implement all the Visit... methods as they already have a default implementation. From what I understood what you want is to find all property accesses of a certain type inside a lambda function

public class MemberAccessVisitor : ExpressionVisitor
{
    private readonly Type declaringType;
    private IList<string> propertyNames = new List<string>();

    public MemberAccessVisitor(Type declaringType)
    {
        this.declaringType = declaringType;
    }

    public IEnumerable<string> PropertyNames { get { return propertyNames; } }

    public override Expression Visit(Expression expr)
    {
        if (expr != null && expr.NodeType == ExpressionType.MemberAccess)
        {
            var memberExpr = (MemberExpression)expr;
            if (memberExpr.Member.DeclaringType == declaringType)
            {
                propertyNames.Add(memberExpr.Member.Name);
            }
        }

        return base.Visit(expr);
    }
}

This could be further improved to what you want by checking the member is a property and also to get PropertyInfo rather than strings

It could be used as follows:

var visitor = new MemberAccessVisitor(typeof(TSource));

visitor.Visit(memberMap);

var propertyNames = visitor.PropertyNames;

 

Traverse an expression tree and extract parameters

标签:sed   fun   ons   further   base   bsp   ado   nbsp   this   

原文地址:https://www.cnblogs.com/chucklu/p/11580209.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!