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會報錯。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM