Reading Properties of an Object with Expression Trees

前端 未结 3 903
太阳男子
太阳男子 2020-12-14 04:40

I want to create a Lambda Expression for every Property of an Object that reads the value dynamically.

What I have so far:

var properties = typeof (T         


        
3条回答
  •  别那么骄傲
    2020-12-14 04:43

    Assuming that you're happy with a Func delegate (as per the comments above), you can use Expression.Convert to achieve that:

    var properties = typeof(TType).GetProperties().Where(p => p.CanRead);
    
    foreach (var propertyInfo in properties)
    {
        MethodInfo getterMethodInfo = propertyInfo.GetGetMethod();
        ParameterExpression entity = Expression.Parameter(typeof(TType));
        MethodCallExpression getterCall = Expression.Call(entity, getterMethodInfo);
    
        UnaryExpression castToObject = Expression.Convert(getterCall, typeof(object));
        LambdaExpression lambda = Expression.Lambda(castToObject, entity);
    
        var functionThatGetsValue = (Func)lambda.Compile();
    }
    

提交回复
热议问题