zoukankan      html  css  js  c++  java
  • 使用表达式树来获取/设置成员的值

            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);

            }
  • 相关阅读:
    POJ ACM题分类
    HDU 4438 Hunters (概率 & 期望)
    HDU 1042 N!
    HDU 1073 Online Judge
    PKU 1006 Biorhythms (中国剩余定理 * *)
    HDU 1047 Integer Inquiry
    HDU 2710 Max Factorv (素数模板 & 多种解法)
    HDU A + B Problem II 1002
    第6期(江西省吉安市永丰县)县长手机信箱工作简报(自吹自擂政绩,自圆其说)
    Send mail from ASP.NET using your gmail account
  • 原文地址:https://www.cnblogs.com/mad/p/1622101.html
Copyright © 2011-2022 走看看