62,272
社区成员
发帖
与我相关
我的任务
分享
namespace JDD_Logic.Sys
{
public delegate string JsonHandler(object obj);
public class JsonService
{
public string SendJson_SQL(object obj)
{
return JsonConvert.SerializeObject(obj);
}
public string SendJson_Ora(object obj)
{
return Convert8859P1ToGB2312(JsonConvert.SerializeObject(obj));
}
public string Convert8859P1ToGB2312(string s)
{
return System.Text.Encoding.Default.GetString(System.Text.Encoding.GetEncoding("iso-8859-1").GetBytes(s));
}
}
}
public void RedisCache1(HttpContext context, Type t, string mth, string key, Type[] ts, object[] o,JsonHandler handler)
{
string json = String.Empty;
if (RedisBase.Item_Exist(key))//判断Redis中,key是否存在;若存在,直接从redis取值,不存在则执行数据库访问方法,这种机制减缓了数据库的压力,提升了系统性能.
{
json = RedisBase.GetValue(key);//根据key获取value
}
else
{
object className = Activator.CreateInstance(t);//反射方法
MethodInfo mInfo = null;
object obj = null;
if (ts != null && o != null)//执行带有多种参数的方法
{
mInfo = t.GetMethod(mth, ts);
obj = mInfo.Invoke(className, o);
}
else//执行无参数的方法
{
mInfo = t.GetMethod(mth);
obj = mInfo.Invoke(className, null);
}
json = handler(obj);
RedisBase.Item_Set<string>(key, json, 120);//根据key设置value
}
context.Response.Write(json);
context.Response.End();
}
public void ShopInfo(HttpContext context)
{
//fth.RedisCache(context, d.GetType(), "GetShop", "ShopInfo", FatherHandler.DataBaseType.SQL_Server);
//fth.RedisCacheForMsSql(context, d.GetType(), "GetShop", "ShopInfo",null,null);
JDD_Logic.Sys.JsonService j=new JDD_Logic.Sys.JsonService();
fth.RedisCache1(context, d.GetType(), "GetShop", "ShopInfo", null, null, j.SendJson_SQL);
}
cmd = (ICommandABC)Activator.CreateInstance(cmdType);
cmd.SetParameters(a,b,c,d);
var result = cmd.Execute();
这里,反射了一个 ICommandABC 实例,然后调用这个接口定义的两个方法。你可以看到,这就不会去考虑什么“想用 Func 泛型实现”的问题,根本不必考虑委托抽象,应该直接用最终业务领域接口来操作。var func =(Func<ABC>) method.CreateDelegate(typeof(Func<ABC>), target);
ABC result = func();
但是如果仅仅调用一次 func 就释放了,那么这个做法显然是得不偿失的。如果你将 Delegate 在进程中缓存起来,成千上万次地复用,那么才能显出 Delegate 调用比 MethodInfo.Invoke 性能更好的特点。
public delegate string JsonHandler<T>(T t);
public string SendJson_SQL<T>(T t)
{
return JsonConvert.SerializeObject(t);
}
public string SendJson_Ora<T>(T t)
{
return Convert8859P1ToGB2312(JsonConvert.SerializeObject(t));
}
在调用委托的时候,还需要指明类型object,这样是不是就没意义了?