首页 > 代码库 > c#反射优化 表达式树
c#反射优化 表达式树
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 = http://www.mamicode.com/Expression.Lambdaobject, object>>(returnObj, param_obj).Compile(); return getValue(obj); } }
c#反射优化 表达式树
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。