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

            }
  • 相关阅读:
    Html5新增视频功能——video API 事件
    HTML5新增的视频功能——video属性
    jQuery封装的tab组件(可选自动+可选延迟处理+按需加载)
    jQuery封装tab选项卡组件(自定义自动功能和延迟显示功能)
    jQuery对象只能使用jQuery提供的方法,不能使用原生js提供的方法
    语法糖 —— 糖糖糖
    面向对象
    Call to undefined function IlluminateEncryptionopenssl_cipher_iv_length()
    HTTP协议
    功能算法
  • 原文地址:https://www.cnblogs.com/mad/p/1622101.html
Copyright © 2011-2022 走看看