使用表达式树来获取/设置成员的值

        public static object GetPropertyValue<T>(this T model, string name)
        {
            var type 
= model.GetType();
            var property 
= type.GetProperty(name);
            
if (property == null)
                
return null;
            
//传参 类型为type
            var getParameter = Expression.Parameter(typeof(T), "model");
            
//把参数T类型转为真实类型
            var convertParameter = Expression.Convert(getParameter, type);
            
//获取属性
            var getProperty = Expression.Property(convertParameter, property);
            
//转为object类型
            var convertProperty = Expression.Convert(getProperty, typeof(object));
            
//生成表达式
            var lambda = Expression.Lambda<Func<T, object>>(convertProperty, getParameter).Compile();
            
return lambda(model);
        }
        
public static void SetPropertyValue<T, TResult>(this T model, string name, TResult value)
        {
            var type 
= model.GetType();

            var p 
= type.GetProperty(name);

            var paramObj 
= Expression.Parameter(type, "obj");

            var paramVal 
= Expression.Parameter(typeof(TResult), "val");

            var body 
= Expression.Call(paramObj, p.GetSetMethod(), paramVal);

            var f 
= Expression.Lambda<Action<T, TResult>>(body, paramObj, paramVal).Compile();

            f(model, value);

        }

 

posted @ 2009-12-11 17:32  君之蘭  阅读(380)  评论(1编辑  收藏  举报