Access the value of a member expression

前端 未结 9 2070
滥情空心
滥情空心 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 08:53

    If you had a class:

    public class Item
    {
        public int Id { get; set; }
    }
    

    and an instance of the object:

    var myItem = new Item { Id = 7 };
    

    You can get the value of Id using an Expression using the following code:

    Expression> exp = x => x.Id;
    var me = exp.Body as MemberExpression;
    var propInfo = me.Member as PropertyInfo;
    var myValue = propInfo.GetValue(myItem, null);
    

    myValue will contain "7"

提交回复
热议问题