Reflect.cs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Reflection;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. namespace ProjectBase.Util
  9. {
  10. /// <summary>
  11. /// 根据业务对象的类型进行反射操作辅助类
  12. /// </summary>
  13. /// <typeparam name="T"></typeparam>
  14. public class Reflect<T> where T : class
  15. {
  16. private static Hashtable ObjCache = new Hashtable();
  17. private static object syncRoot = new Object();
  18. /// <summary>
  19. /// 根据参数创建对象实例
  20. /// </summary>
  21. /// <param name="sName">对象全局名称</param>
  22. /// <param name="sFilePath">文件路径</param>
  23. /// <returns></returns>
  24. public static T Create(string sName, string sFilePath)
  25. {
  26. return Create(sName, sFilePath, true);
  27. }
  28. /// <summary>
  29. /// 根据参数创建对象实例
  30. /// </summary>
  31. /// <param name="sName">对象全局名称</param>
  32. /// <param name="sFilePath">文件路径</param>
  33. /// <param name="bCache">缓存集合</param>
  34. /// <returns></returns>
  35. public static T Create(string sName, string sFilePath, bool bCache)
  36. {
  37. string CacheKey = sName;
  38. T objType = null;
  39. if (bCache)
  40. {
  41. objType = (T)ObjCache[CacheKey]; //从缓存读取
  42. if (!ObjCache.ContainsKey(CacheKey))
  43. {
  44. lock (syncRoot)
  45. {
  46. objType = CreateInstance(CacheKey, sFilePath);
  47. ObjCache.Add(CacheKey, objType);//缓存数据访问对象
  48. }
  49. }
  50. }
  51. else
  52. {
  53. objType = CreateInstance(CacheKey, sFilePath);
  54. }
  55. return objType;
  56. }
  57. /// <summary>
  58. /// 根据全名和路径构造对象
  59. /// </summary>
  60. /// <param name="sName">对象全名</param>
  61. /// <param name="sFilePath">程序集路径</param>
  62. /// <returns></returns>
  63. private static T CreateInstance(string sName, string sFilePath)
  64. {
  65. Assembly assemblyObj = Assembly.Load(sFilePath);
  66. if (assemblyObj == null)
  67. {
  68. throw new ArgumentNullException("sFilePath", string.Format("无法加载sFilePath={0} 的程序集", sFilePath));
  69. }
  70. T obj = (T)assemblyObj.CreateInstance(sName); //反射创建
  71. return obj;
  72. }
  73. }
  74. }