如何在C#中使用Reflection获取Expression的Object.Value

时间:2017-11-08 16:09:58

标签: c# reflection expression

我想得到一个列表的值。我的方法是这样的:

 private void predicateTest(Expression<Func<bool>> predicate)
        {
            var body = predicate.Body;

            var binaryExpression = body as BinaryExpression;
            var binaryBody= binaryExpression ??    
                        Expression.MakeBinary(ExpressionType.Equal, 
                        body, Expression.Constant(true));
            var left = binaryBody.Left;
        }

我的呼唤:

List<string> list = new List<string> { "doc", "exe", "jpg" };

predicateTest(() => list.Contains("sdf"));

和谓词.Body.Left值如下图。 如何在predicateTest方法中将list的值作为programmatic?

enter image description here

1 个答案:

答案 0 :(得分:0)

以下传递:

    private List<string> predicateTest(Expression<Func<bool>> predicate)
    {
        var body = predicate.Body;

        var binaryExpression = body as BinaryExpression;
        var binaryBody = binaryExpression ??
                    Expression.MakeBinary(ExpressionType.Equal,
                    body, Expression.Constant(true));
        var left = binaryBody.Left;

        return Expression.Lambda(((MethodCallExpression)left).Object).Compile().DynamicInvoke() as List<string>;
    }

    [Test]
    public void PredicateTest_ShouldFindList()
    {
        List<string> list = new List<string> { "doc", "exe", "jpg" };
        var result = predicateTest(() => list.Contains("sdf"));
        Assert.That(list, Is.SameAs(result));
    }

当然,如果您的表达形式与您所表达的格式略有不同,您将获得各种例外情况。从可能采用各种形式的表达式中解析您想要的内容的能力是Ed推荐的访问者的好处之一。