以下是我的课程:

public class A
{
    public int i { get; set; }
}

public class B
{
    public A a { get; set; }
    public int j { get; set; }
}


如果我想使用表达式来表达b.j>3,我可以这样做:

ParameterExpression parameter = Expression.Parameter(typeof(B), "b");
MemberExpression member = Expression.PropertyOrField(parameter, "j");
ConstantExpression constant = Expression.Constant(3);
return Expression.Lambda<Func<B, bool>>(Expression.GreaterThan(member, constant), parameter);


现在,如何为b.a.i>3构建表达式?

最佳答案

只需根据前一个创建另一个MemberExpression

ParameterExpression parameter = Expression.Parameter(typeof(B), "b");
MemberExpression memberA = Expression.PropertyOrField(parameter, "a");

// Use the previous MemberExpression here:
MemberExpression memberI = Expression.PropertyOrField(memberA, "i");

ConstantExpression constant = Expression.Constant(3);
return Expression.Lambda<Func<B, bool>>(Expression.GreaterThan(memberI, constant), parameter);

关于c# - 如何建立memberexpression的memberexpression?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54942629/

10-09 12:30