用法很简单:

ReflectionSugar rs = new ReflectionSugar(100);//缓存100秒 ,可以不填默认不缓存

rs.有嘛点嘛

 

性能测试:

性能测试类源码:

http://www.cnblogs.com/sunkaixuan/p/4540840.html

  1. using SyntacticSugar;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Reflection;
  6. using System.Web;
  7. using System.Web.UI;
  8. using System.Web.UI.WebControls;
  9.  
  10. namespace Test.IO
  11. {
  12. public partial class ReflectionTest : System.Web.UI.Page
  13. {
  14. protected void Page_Load(object sender, EventArgs e)
  15. {
  16. //性能测试类
  17. PerformanceTest p = new PerformanceTest();
  18. p.SetCount(100000);//循环次数(默认:1)
  19. p.SetIsMultithread(false);//是否启动多线程测试 (默认:false)
  20.  
  21. /******************************CreateInstance********************************/
  22. //带cache
  23. p.Execute(
  24. i =>
  25. {
  26. CreateInstanceByCache();//调用函数
  27. },
  28. message => { Response.Write(message); }); //总共执行时间:0.09901秒
  29.  
  30. //不带cache
  31. p.Execute(
  32. i =>
  33. {
  34. CreateInstanceNoCache();//调用函数
  35. },
  36. message => { Response.Write(message); }); //总共执行时间:0.32002秒
  37.  
  38. /******************************ExecuteMethod********************************/
  39. //带cache
  40. p.Execute(
  41. i =>
  42. {
  43. ExecuteMethodByCache();//调用函数
  44. },
  45. message => { Response.Write(message); }); //总共执行时间:0.36202秒
  46.  
  47. //不带cache
  48. p.Execute(
  49. i =>
  50. {
  51. ExecuteMethodNoCache();//调用函数
  52. },
  53. message => { Response.Write(message); }); //总共执行时间:1.35508秒
  54.  
  55. /******************************ExecuteMethod********************************/
  56. //带cache
  57. p.Execute(
  58. i =>
  59. {
  60. ExecuteMethodByCache();//调用函数
  61. },
  62. message => { Response.Write(message); }); //总共执行时间:0.36202秒
  63.  
  64. //不带cache
  65. p.Execute(
  66. i =>
  67. {
  68. ExecuteMethodNoCache();//调用函数
  69. },
  70. message => { Response.Write(message); }); //总共执行时间:1.35508秒
  71.  
  72. /******************************LoadFile********************************/
  73. //带cache
  74. p.Execute(
  75. i =>
  76. {
  77. LoadFileByCache();//调用函数
  78. },
  79. message => { Response.Write(message); }); //总共执行时间:0.11801
  80.  
  81. //不带cache
  82. p.Execute(
  83. i =>
  84. {
  85. LoadFileNoCache();//调用函数
  86. },
  87. message => { Response.Write(message); }); //总共执行时间:4.89628秒
  88.  
  89. //还有其它方法就不测试了
  90. }
  91.  
  92. //获取实列
  93. private static void CreateInstanceByCache()
  94. {
  95. ReflectionSugar rs = new ReflectionSugar(100);//缓存100秒
  96. var f = rs.CreateInstance<FileSugar>("SyntacticSugar.FileSugar", "SyntacticSugar");
  97. }
  98. //获取实列
  99. private static void CreateInstanceNoCache()
  100. {
  101. string path = "SyntacticSugar.FileSugar,SyntacticSugar";//命名空间.类型名,程序集
  102. Type o = Type.GetType(path);//加载类型
  103. FileSugar obj = (FileSugar)Activator.CreateInstance(o, true);//根据类型创建实例
  104. }
  105. //执行函数
  106. private static void ExecuteMethodByCache()
  107. {
  108. ReflectionSugar rs = new ReflectionSugar(100);//缓存100秒
  109. var path = rs.ExecuteMethod("SyntacticSugar", "FileSugar", "GetMapPath", "~/");
  110. }
  111. //执行函数
  112. private static void ExecuteMethodNoCache()
  113. {
  114. ReflectionSugar rs = new ReflectionSugar(0);//缓存0秒
  115. var path = rs.ExecuteMethod("SyntacticSugar", "FileSugar", "GetMapPath", "~/");
  116. }
  117. //加载程序集
  118. private static void LoadFileByCache()
  119. {
  120. ReflectionSugar rs = new ReflectionSugar(100);//缓存100秒
  121. Assembly ams = rs.LoadFile(@"D:\学习\SyntacticSugar\SyntacticSugar\bin\Debug\SyntacticSugar.dll");
  122. }
  123. //加载程序集
  124. private static void LoadFileNoCache()
  125. {
  126. ReflectionSugar rs = new ReflectionSugar(0);//缓存100秒
  127. Assembly ams = rs.LoadFile(@"D:\学习\SyntacticSugar\SyntacticSugar\bin\Debug\SyntacticSugar.dll");
  128. }
  129. }
  130. }

  

反射类源码: 

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Reflection;
  5. using System.Text;
  6. using System.Web;
  7. using System.Web.Caching;
  8.  
  9. namespace SyntacticSugar
  10. {
  11.  
  12. /// <summary>
  13. /// ** 描述:反射通用类
  14. /// ** 创始时间:2010-2-28
  15. /// ** 修改时间:-
  16. /// ** 修改人:sunkaixuan
  17. /// ** 使用说明: http://www.cnblogs.com/sunkaixuan/p/4635710.html
  18. /// </summary>
  19. public class ReflectionSugar
  20. {
  21. public static int Minutes = 60;
  22. public static int Hour = 60 * 60;
  23. public static int Day = 60 * 60 * 24;
  24. private int _time = 0;
  25. private bool _isCache { get { return _time > 0; } }
  26. /// <summary>
  27. /// 缓存时间,0为不缓存(默认值:0秒,单位:秒)
  28. /// </summary>
  29. public ReflectionSugar(int time = 0)
  30. {
  31. _time = time;
  32. }
  33.  
  34. /// <summary>
  35. /// 创建对象实例
  36. /// </summary>
  37. /// <typeparam name="T"></typeparam>
  38. /// <param name="fullName">命名空间.类型名</param>
  39. /// <param name="assemblyName">程序集(dll名称)</param>
  40. /// <returns></returns>
  41. public T CreateInstance<T>(string fullName, string assemblyName)
  42. {
  43. string key = GetKey("CreateInstance1", fullName, assemblyName);
  44. if (_isCache)
  45. if (ContainsKey(key))
  46. {
  47. return Get<T>(key);
  48. }
  49. string path = fullName + "," + assemblyName;//命名空间.类型名,程序集
  50. Type o = Type.GetType(path);//加载类型
  51. object obj = Activator.CreateInstance(o, true);//根据类型创建实例
  52. var reval = (T)obj;
  53. if (_isCache)
  54. Add<T>(key, reval, _time);
  55. return reval;//类型转换并返回
  56. }
  57.  
  58. /// <summary>
  59. /// 创建对象实例
  60. /// </summary>
  61. /// <typeparam name="T">要创建对象的类型</typeparam>
  62. /// <param name="assemblyName">类型所在程序集名称(dll名称)</param>
  63. /// <param name="nameSpace">类型所在命名空间</param>
  64. /// <param name="className">类型名</param>
  65. /// <returns></returns>
  66. public T CreateInstance<T>(string assemblyName, string nameSpace, string className)
  67. {
  68. string key = GetKey("CreateInstance2", assemblyName, nameSpace, className);
  69. if (_isCache)
  70. if (ContainsKey(key))
  71. {
  72. return Get<T>(key);
  73. }
  74. try
  75. {
  76. string fullName = nameSpace + "." + className;//命名空间.类型名
  77. //此为第一种写法
  78. object ect = Assembly.Load(assemblyName).CreateInstance(fullName);//加载程序集,创建程序集里面的 命名空间.类型名 实例
  79. var reval = (T)ect;//类型转换并返回
  80. if (_isCache)
  81. Add<T>(key, reval, _time);
  82. return reval;
  83. //下面是第二种写法
  84. //string path = fullName + "," + assemblyName;//命名空间.类型名,程序集
  85. //Type o = Type.GetType(path);//加载类型
  86. //object obj = Activator.CreateInstance(o, true);//根据类型创建实例
  87. //return (T)obj;//类型转换并返回
  88. }
  89. catch
  90. {
  91. //发生异常,返回类型的默认值
  92. var reval = default(T);
  93. if (_isCache)
  94. Add<T>(key, reval, _time);
  95. return reval;//类型转换
  96. }
  97. }
  98. /// <summary>
  99. /// 加载程序集
  100. /// </summary>
  101. /// <param name="path"></param>
  102. /// <returns></returns>
  103. public Assembly LoadFile(string path)
  104. {
  105. string key = GetKey("LoadFile", path);
  106. if (_isCache)
  107. if (ContainsKey(key))
  108. {
  109. return Get<Assembly>(key);
  110. }
  111. Assembly asm = Assembly.LoadFile(path);
  112. if (_isCache)
  113. Add<Assembly>(key, asm, _time);
  114. return asm;
  115. }
  116.  
  117. /// <summary>
  118. /// 获取类型根据程序集
  119. /// </summary>
  120. /// <param name="asm">Assembly对象</param>
  121. /// <returns></returns>
  122. public Type GetTypeByAssembly(Assembly asm, string nameSpace, string className)
  123. {
  124. string key = GetKey("GetTypeByAssembly", nameSpace, className);
  125. if (_isCache)
  126. if (ContainsKey(key))
  127. {
  128. return Get<Type>(key);
  129. }
  130. Type type = asm.GetType(nameSpace + "." + className);
  131. if (_isCache)
  132. Add<Type>(key, type, _time);
  133. return type;
  134. }
  135.  
  136. /// <summary>
  137. /// 返回当前 System.Type 的所有公共属性。
  138. /// </summary>
  139. /// <param name="type"></param>
  140. /// <returns></returns>
  141. public PropertyInfo[] GetProperties(Type type)
  142. {
  143. string key = GetKey("GetProperties", type.FullName);
  144. if (_isCache)
  145. if (ContainsKey(key))
  146. {
  147. return Get<PropertyInfo[]>(key);
  148. }
  149. var reval = type.GetProperties();
  150. if (_isCache)
  151. Add<PropertyInfo[]>(key, reval, _time);
  152. return reval;
  153. }
  154.  
  155. /// <summary>
  156. /// 根据字符执行方法
  157. /// </summary>
  158. /// <param name="nameSpace">命名空间</param>
  159. /// <param name="className">类名</param>
  160. /// <param name="MethodName">方法名</param>
  161. /// <param name="parameters">参数</param>
  162. /// <returns>返回object类型</returns>
  163. public object ExecuteMethod(string nameSpace, string className, string MethodName, params object[] parameters)
  164. {
  165. string key = GetKey("ExecuteMethod", nameSpace, className, MethodName, parameters.Length.ToString());
  166. MethodInfo methodinfo = null;
  167. if (_isCache&&ContainsKey(key))
  168. {
  169. methodinfo = Get<MethodInfo>(key);
  170. }
  171. else
  172. {
  173. //动态从程序集中查找所需要的类并使用系统激活器创建实例最后获取它的Type
  174. Type type = Assembly.Load(nameSpace).CreateInstance(nameSpace + "." + className).GetType();
  175. //定义参数的个数,顺序以及类型的存储空间;
  176. Type[] parametersLength;
  177. if (parameters != null)
  178. {
  179.  
  180. //如果有参数创建参数存储空间并依次设置类型
  181. parametersLength = new Type[parameters.Length];
  182. int i = 0;
  183. foreach (object obj in parameters)
  184. {
  185.  
  186. parametersLength.SetValue(obj.GetType(), i);
  187. i++;
  188.  
  189. }
  190.  
  191. }
  192. else
  193. {
  194.  
  195. //没有参数就为空
  196. parametersLength = new Type[0];
  197.  
  198. }
  199.  
  200. //查找指定的方法
  201. methodinfo = type.GetMethod(MethodName, parametersLength);
  202. if (_isCache)
  203. Add<MethodInfo>(key, methodinfo, _time);
  204. }
  205. //如果是静态方法就执行(非静态我没试过)
  206. if (methodinfo.IsStatic)
  207. {
  208.  
  209. //调用函数
  210. return methodinfo.Invoke(null, parameters);
  211.  
  212. }
  213.  
  214. return null;
  215.  
  216. }
  217.  
  218. #region helper
  219. private string GetKey(params string[] keyElementArray)
  220. {
  221. return string.Join("", keyElementArray);
  222. }
  223.  
  224. /// <summary>
  225. /// 插入缓存
  226. /// </summary>
  227. /// <param name="key"> key</param>
  228. /// <param name="value">value</param>
  229. /// <param name="cacheDurationInSeconds">过期时间单位秒</param>
  230. private void Add<V>(string key, V value, int cacheDurationInSeconds)
  231. {
  232. Add(key, value, cacheDurationInSeconds, CacheItemPriority.Default);
  233. }
  234.  
  235. /// <summary>
  236. /// 插入缓存.
  237. /// </summary>
  238. /// <param name="key">key</param>
  239. /// <param name="value">value</param>
  240. /// <param name="cacheDurationInSeconds">过期时间单位秒</param>
  241. /// <param name="priority">缓存项属性</param>
  242. private void Add<V>(string key, V value, int cacheDurationInSeconds, CacheItemPriority priority)
  243. {
  244. string keyString = key;
  245. HttpRuntime.Cache.Insert(keyString, value, null, DateTime.Now.AddSeconds(cacheDurationInSeconds), Cache.NoSlidingExpiration, priority, null);
  246. }
  247.  
  248. /// <summary>
  249. /// 插入缓存.
  250. /// </summary>
  251. /// <param name="key">key</param>
  252. /// <param name="value">value</param>
  253. /// <param name="cacheDurationInSeconds">过期时间单位秒</param>
  254. /// <param name="priority">缓存项属性</param>
  255. private void Add<V>(string key, V value, int cacheDurationInSeconds, CacheDependency dependency, CacheItemPriority priority)
  256. {
  257. string keyString = key;
  258. HttpRuntime.Cache.Insert(keyString, value, dependency, DateTime.Now.AddSeconds(cacheDurationInSeconds), Cache.NoSlidingExpiration, priority, null);
  259. }
  260.  
  261. /// <summary>
  262. /// key是否存在
  263. /// </summary>
  264. /// <param name="key">key</param>
  265. /// <returns> /// 存在<c>true</c> 不存在<c>false</c>. /// /// </returns>
  266. private bool ContainsKey(string key)
  267. {
  268. return HttpRuntime.Cache[key] != null;
  269. }
  270.  
  271. /// <summary>
  272. ///获取Cache根据key
  273. /// </summary>
  274. private V Get<V>(string key)
  275. {
  276. return (V)HttpRuntime.Cache[key];
  277. }
  278. #endregion
  279.  
  280. //PropertyInfo GET SET说明
  281. //T.GetProperty("key").GetValue(obj, null); //read a key value
  282. //T.GetProperty("key").SetValue(obj, "", null); //write a value to key
  283. ////注意如果是字典
  284. //T.GetProperty("Item").GetValue(obj, new [] {"id"}); //先拿Item 然后才通过 new[] {这里放指定的key}
  285. }
  286. }

  

总结:

只要不反射外部DLL文件缓存可以提高3倍性能,如果是反射外部DLL文件可以提高40倍以上,这只是我的测试结果 循环次数超多性能差距越大

C#语法糖之 ReflectionSugar 通用反射类的更多相关文章

  1. ReflectionSugar 通用反射类

    http://www.cnblogs.com/sunkaixuan/p/4635710.html

  2. Scala的apply unapply unapplySeq 语法糖

    apply 可以理解为注入 unapply unapplySeq 可以理解为提取 apply 与 unapply 虽然名字相近,但是使用起来区别挺大.apply有点像构造函数unapply主要是结合模 ...

  3. Python进阶-XVIII 封装、(属性、静态方法、类方法)语法糖、反射

    1.封装 类中的私有化:属性的私有化和方法的私有化 会用到私有的这个概念de场景 1.隐藏起一个属性 不想让类的外部调用 2.我想保护这个属性,不想让属性随意被改变 3.我想保护这个属性,不被子类继承 ...

  4. Java语法糖设计

    语法糖 Java语法糖系列,所以首先讲讲什么是语法糖.语法糖是一种几乎每种语言或多或少都提供过的一些方便程序员开发代码的语法,它只是编译器实现的一些小把戏罢了,编译期间以特定的字节码或者特定的方式对这 ...

  5. 看看C# 6.0中那些语法糖都干了些什么(中篇)

    接着上篇继续扯,其实语法糖也不是什么坏事,第一个就是吃不吃随你,第二个就是最好要知道这些糖在底层都做了些什么,不过有一点 叫眼见为实,这样才能安心的使用,一口气上五楼,不费劲. 一:字符串嵌入值 我想 ...

  6. C# 6.0新特性---语法糖

    转载:http://www.cnblogs.com/TianFang/p/3928172.html 所谓语法糖就是在编译器里写做文章,达到简化代码书写的目的,要慎重使用,省略过多不易理解. NULL检 ...

  7. 语法糖----JAVA

    语法糖 语法糖(Syntactic Sugar),也叫糖衣语法,是英国计算机科学家彼得·约翰·兰达(Peter J. Landin)发明的一个术语.指的是,在计算机语言中添加某种语法,这种语法能使程序 ...

  8. 语法糖(Syntactic sugar)

    语法糖(Syntactic sugar),是由Peter J. Landin(和图灵一样的天才人物,是他最先发现了Lambda演算,由此而创立了函数式编程)创造的一个词语,它意指那些没有给计算机语言添 ...

  9. 早期(编译器)优化--Java语法糖的味道

    1.泛型与类型擦除 泛型的本质是参数化类型的应用,也就是说所操作的数据类型被指定为一个参数.这种参数类型可以用在类.接口和方法的创建中,分别称为泛型类.泛型接口和泛型方法.在泛型没有出现之前,只能通过 ...

随机推荐

  1. DNS劫持

    忽然发现我最喜欢的chrome 一直有广告,好些论坛都有大量的广告,原以为是重了什么插件了,找了也没发现,有可能是DNS劫持. 打开路由器,找到 dns 设置里面把里面的全部去掉.然后把 192.16 ...

  2. json字符串转成 Map/List

    package jsonToMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import n ...

  3. Gradle 构建 android 应用常见问题解决指南

    前言 android gradle 插件已经发展到0.5.7,同时gradle 本身也到了1.8,相比两个月前,android gradle 更快,更完善,也更好用了,为了让各位androider 早 ...

  4. asp.net 后台实现删除,划掉效果

    效果: name = "<S>" + fircon + "</br>" + "</S>"; 增加“< ...

  5. 用飞信监控GoldenGate进程

    监控GoldenGate进程 1)         在goldengate安装目录下建立文件ogginfo $vim ogginfo  info all 2)         配置飞信报警       ...

  6. 阿里云 Redis 服务遇到的问题

    ERR unknown command eval 说明: 执行当前 Web 请求期间,出现未经处理的异常.请检查堆栈跟踪信息,以了解有关该错误以及代码中导致错误的出处的详细信息. 异常详细信息: St ...

  7. sql读取xml

    DECLARE @ItemMessage XML SET @ItemMessage=cast(N'<?xml version="1.0" encoding="utf ...

  8. 做最好的日期控件,My97 DatePicker 4.8 Beta4

    4.8更新的内容 [新增]preload预载选项 [新增]时分秒选择菜单的定制功能,详见hmsMenuCfg属性[beta4] [新增]$dp.unbind函数,允许用户手动接触日期控件绑定[beta ...

  9. MySql批量更新方法

    准备数据 表 user(用户).dept(部门) 1:更新符合单个条件的某个字段的一条数据 update user u set u.name = '测试' where u.id = "&qu ...

  10. 实例学习Backbone.js(一)

    前面有两篇文章介绍了Backbone的model.collection和view,那么接下来我想用一个完整的Demo来记录我学习的过程, 单页操作,实现数据的增删改,后台使用json做数据库,通过re ...