標籤: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#反射最佳化 運算式樹狀架構