c#反射优化 表达式树
Posted 听哥哥的话
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 = Expression.Lambda<Func<object, object>>(returnObj, param_obj).Compile(); return getValue(obj); } }
以上是关于c#反射优化 表达式树的主要内容,如果未能解决你的问题,请参考以下文章
优化 C# 代码片段、ObservableCollection 和 AddRange