简体   繁体   中英

How to get value of a property?

I have a class that derives from ExpressionVistor , and I'm trying to parse an expression such as:

x => x.MyProperty != otherClass.OtherProperty;

I'm overriding VisitMember:

protected override Expression VisitMember(MemberExpression m)
{
    if (m.Expression != null && m.Expression.NodeType == ExpressionType.MemberAccess)
    {
        var info = m.Member;

        return m;
    }
}

But how do I get the property value?

In order to get a value, you need the Member owner ( Expression property - the containing object of the field or property ) to be either null (for static property/field), ConstantExpression or another MemberAcccessExpression (there are also other scenarios, but here we speak about simple objA.propA.propB.propC accessors). Which leads to a recursive helper method like this:

static bool TryGetValue(MemberExpression me, out object value)
{
    object source = null;
    if (me.Expression != null)
    {
        if (me.Expression.NodeType == ExpressionType.Constant)
            source = ((ConstantExpression)me.Expression).Value;
        else if (me.Expression.NodeType != ExpressionType.MemberAccess
            || !TryGetValue((MemberExpression)me.Expression, out source))
        {
            value = null;
            return false;
        }
    }
    if (me.Member is PropertyInfo)
        value = ((PropertyInfo)me.Member).GetValue(source);
    else
        value = ((FieldInfo)me.Member).GetValue(source);
    return true;
}

so you can use it like this:

protected override Expression VisitMember(MemberExpression m)
{
    object value;
    if (TryGetValue(m, out value))
    {
        // Use the value
    }

    return m;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM