获取实体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会报错。

相关文章:

  • 2021-09-23
  • 2021-07-01
  • 2021-05-23
  • 2022-12-23
  • 2021-12-06
  • 2022-12-23
猜你喜欢
  • 2022-03-04
  • 2021-06-06
  • 2021-10-20
  • 2021-11-04
  • 2021-07-19
相关资源
相似解决方案