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

            }
  • 相关阅读:
    VS2013 自动添加头部注释 -C#开发
    在调用Response.End()时,会执行Thread.CurrentThread.Abort()操作
    React
    WebApi基础
    wcf
    memcached系列
    Ioc容器Autofac系列
    使用TortoiseSVN创建版本库
    使用libcurl 发送post请求
    值得推荐的C/C++框架和库
  • 原文地址:https://www.cnblogs.com/mad/p/1622101.html
Copyright © 2011-2022 走看看