c#反射优化 表达式树

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using System.Web; namespace Holworth.Utility
{
//add modi by kexb 2016年11月5日
public static class FastRefelect
{
private static Spring.Caching.ICache GetSpringCache()
{
var ctx = Spring.Context.Support.ContextRegistry.GetContext();
var cache = (Spring.Caching.ICache)ctx.GetObject("AspNetCache");
return cache;
}
public static void AddCache(string key, object value)
{
var cache = GetSpringCache();
cache.Insert(key, value);
}
public static void RemoveCache(string key)
{
var cache = GetSpringCache();
cache.Remove(key);
}
public static object GetSpringCache(string key)
{
var cache = GetSpringCache();
return cache.Get(key);
} public static Func<T, MethodInfo, object, object> GetSetDelegate<T>(MethodInfo m, Type propertyType,string typeName)
{
Action<T, MethodInfo, object> set = null;
string key = typeName + "," + m.Name+","+propertyType.Name+"," + "_FAST_SET_DELEGATE";
if (GetSpringCache(key) == null)
{
Type mO = typeof(object);
Type mT = typeof(T);
Type mType = typeof(MethodInfo); 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, propertyType);
var body = Expression.Call(param_obj, m, body_val);
set = Expression.Lambda<Action<T, MethodInfo, object>>(body, param_obj, param_m, param_val).Compile();
AddCache(key, set);
}
else
{
set = (Action<T, MethodInfo, object>)GetSpringCache(key); }
return (instance, method, v) =>
{
set(instance, method, v);
return null; }; } public static void FastSetValue<T>(this PropertyInfo property, T t, string typeName, object value)
{ string key = typeName + "," + property.Name + "_FAST_METHOD_INFO";
MethodInfo m = null;
if (GetSpringCache(key) == null)
{
m = property.GetSetMethod();
AddCache(key, m);
}
else
{
m = (MethodInfo)GetSpringCache(key);
} GetSetDelegate<T>(m, property.PropertyType,typeName)(t, m, value);
}
public static object FastGetValue<T>(this object obj, string TypeName, string TProperty)
{
string key = TypeName + "," + TProperty + "_FAST_REFELECT";
Func<object, object> getValue = null;
if (GetSpringCache(key) == null)
{
Type SelfType = Type.GetType(TypeName);
//lambda的参数u
var param_obj = Expression.Parameter(typeof(object), "obj");
//类型转换
var convert_obj = Expression.Convert(param_obj, SelfType);
//lambda的方法体 ((MyMath)obj).Age
var pGetter = Expression.Property(convert_obj, TProperty);
//对返回值进行类型转换
var returnObj = Expression.Convert(pGetter, typeof(object));
//编译lambda
getValue = Expression.Lambda<Func<object, object>>(returnObj, param_obj).Compile();
AddCache(key, getValue);
}
else
{
getValue = (Func<object, object>)GetSpringCache(key); }
return getValue(obj);
}
}
}
上一篇:深入应用linux及其它开源产品


下一篇:[复习] JAVA 遍历目录 (递归调用和非递归)