Getting the object out of a MemberExpression?

前端 未结 5 1825
野性不改
野性不改 2020-11-30 23:33

So, lets say I have the following expression in C#:

Expression> expr = () => foo.Bar;

How do I pull out a refer

5条回答
  •  独厮守ぢ
    2020-11-30 23:58

    Thanks, staks - your example helped me a lot! So i'd like to contribute with some addition to the first case:

    To extract values from methods, one should replace code:

    // fetch the root object reference:
    var constExpr = expr as ConstantExpression;
    var objReference = constExpr.Value;
    

    with code:

        var newExpression = expr as NewExpression;
        if (newExpression != null)
        {                
            return newExpression.Constructor.Invoke(newExpression.Arguments.Select(GetObjectValue).ToArray());
        }
    
        var methodCallExpr = expr as MethodCallExpression;
        if (methodCallExpr != null)
        {
            var value = methodCallExpr.Method.Invoke(methodCallExpr.Object == null
                                                                     ? null
                                                                     : GetObjectValue(methodCallExpr.Object),
    methodCallExpr.Arguments.Select(GetObjectValue).ToArray());
                        return value;
        }
    
        // fetch the root object reference:
        var constExpr = expr as ConstantExpression;
        if (constExpr == null)
        {
             return null;
        }
        var objReference = constExpr.Value;
        // ... the rest remains unchanged
    

    that way one could extract values from expressions like:

    aInstane.MethodCall(anArgument1, anArgument2) or
    AType.MethodCall(anArgument1, anArgument2) or
    new AType().MethodCall(anArgument1, aInstane.MethodCall(anArgument2, anArgument3))
    

提交回复
热议问题