码迷,mamicode.com
首页 > Windows程序 > 详细

c#反射优化 表达式树

时间:2016-11-05 22:39:19      阅读:511      评论:0      收藏:0      [点我收藏+]

标签:style   turn   code   转换   eth   bsp   ring   res   type   

   public static class FastRefelect
    {
        static Type pType;
        static object cmp;
        static Type mO;
        static Type mT;
        static Type mType;
        static MethodInfo m;
        static int i = 0;
        static int k = 0;
        public static Func<T, MethodInfo, object, object> GetSetDelegate<T>(MethodInfo m, Type type)
        {
            Action<T, MethodInfo, object> set = null;


            if (k == 0)
            {
                var param_obj = Expression.Parameter(mT, "obj");
                var param_val = Expression.Parameter(mO, "val");
                var param_m = Expression.Parameter(mType, "m");
                var body_val = Expression.Convert(param_val, type);
                var body = Expression.Call(param_obj, m, body_val);
                set = Expression.Lambda<Action<T, MethodInfo, object>>(body, param_obj, param_m, param_val).Compile();
                cmp = set;
                k++;
            }
            else
            {
                set = (Action<T, MethodInfo, object>)cmp;
            }

            return (instance, method, v) =>
            {
                set(instance, method, v);
                return null;

            };

        }

        public static void FastSetValue<T>(this PropertyInfo property, T t, object value)
        {
            if (i == 0)
            {
                pType = property.PropertyType;
                mO = typeof(object);
                mT = typeof(T);
                mType = typeof(MethodInfo);
                m = property.GetSetMethod();
                i++;
            }

            GetSetDelegate<T>(m, pType)(t, m, value);
        }
        public static object FastGetValue<T>(this object obj,System.Linq.Expressions.Expression<Func<T,string>> TProperty)
        {
            var type = obj.GetType();
            //做缓存
            var p = type.GetProperty(TProperty.Body.ToString().Split(.)[1]);
            //lambda的参数u 
            var param_obj = Expression.Parameter(typeof(object), "obj");
            //类型转换
            var convert_obj = Expression.Convert(param_obj, type);
            //lambda的方法体 ((MyMath)obj).Age
            var pGetter = Expression.Property(convert_obj, p);
            //对返回值进行类型转换
            var returnObj = Expression.Convert(pGetter, typeof(object));
            //编译lambda 
            var getValue = Expression.Lambda<Func<object, object>>(returnObj, param_obj).Compile();
            return getValue(obj);
        }
    }

 

c#反射优化 表达式树

标签:style   turn   code   转换   eth   bsp   ring   res   type   

原文地址:http://www.cnblogs.com/kexb/p/6033973.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!