zoukankan      html  css  js  c++  java
  • c# 动态构造实体属性的lambda Expression表达式

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

  • 相关阅读:
    事务的隔离级别
    事务的隔离
    事务简介
    leetcode647
    leetcode394
    leetcode96
    leetcode814
    leetcode738
    leetcode621
    leetcode763
  • 原文地址:https://www.cnblogs.com/hankuikui/p/12918247.html
Copyright © 2011-2022 走看看