获取实体T的所有属性的lambda表达式数组:
如x->x.a,x->x.b,x->x.b,x->x.c
public static Expression<Func<T, object>>[] GetExpressions<T>() { var properties = typeof(T).GetProperties(); Expression<Func<T, object>>[] expressions = new Expression<Func<T, object>>[properties.Length]; var p = Expression.Parameter(typeof(T), "x"); for (int i = 0; i < properties.Length; i++) { Expression exProperty = Expression.Property(p, properties[i]); var body = Expression.Convert(exProperty, typeof(object)); expressions[i] = Expression.Lambda<Func<T, object>>(body, p); } return expressions; }
为什么要加var body = Expression.Convert(exProperty, typeof(object));
因为如果我们的属性的类型为decimal?等可空类型时,不加convert会报错。