Access the value of a member expression

前端 未结 9 2053
滥情空心
滥情空心 2020-12-04 08:33

If i have a product.

var p = new Product { Price = 30 };

and i have the following linq query.

var q = repo.Products().Where         


        
9条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-04 09:12

    The constant expression is going to point to a capture-class generated by the compiler. I've not included the decision points etc, but here's how to get 30 from that:

    var p = new Product { Price = 30 };
    Expression> predicate = x => x.Price == p.Price;
    BinaryExpression eq = (BinaryExpression)predicate.Body;
    MemberExpression productToPrice = (MemberExpression)eq.Right;
    MemberExpression captureToProduct = (MemberExpression)productToPrice.Expression;
    ConstantExpression captureConst = (ConstantExpression)captureToProduct.Expression;
    object product = ((FieldInfo)captureToProduct.Member).GetValue(captureConst.Value);
    object price = ((PropertyInfo)productToPrice.Member).GetValue(product, null);
    

    price is now 30. Note that I'm assuming that Price is a property, but in reality you would write a GetValue method that handles property / field.

提交回复
热议问题