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 namespace LYZB.ApiConfig 8 { 9 /// <summary> 10 /// 自定义工厂类 11 /// </summary> 12 /// <typeparam name="T">泛型</typeparam> 13 public abstract class AssesUtil<T> where T : class,new() 14 { 15 /// <summary> 16 /// 缓存集合 17 /// </summary> 18 private static Hashtable hash = Hashtable.Synchronized(new Hashtable()); 19 /// <summary> 20 /// 执行实例方法 21 /// </summary> 22 /// <param name="FunName">方法名</param> 23 /// <param name="type">参数类型</param> 24 /// <param name="arg">参数实体</param> 25 /// <returns></returns> 26 public static object Invoke(string FunName, Type[] type, params object[] arg) 27 { 28 object result = null; 29 try 30 { 31 Type types = typeof(T); 32 var classname = types.Namespace + "." + types.Name; 33 MethodInfo method = types.GetMethod(FunName, type); 34 if (hash[classname] != null) 35 { 36 result = method.Invoke(hash[classname], arg); 37 } 38 else 39 { 40 var func = Activator.CreateInstance(types); 41 result = method.Invoke(func, arg); 42 hash[classname] = func; 43 } 44 } 45 catch (Exception e) 46 { 47 throw e; 48 } 49 return result; 50 } 51 /// <summary> 52 /// 高并发执行方法 53 /// </summary> 54 /// <param name="FunName">方法名</param> 55 /// <param name="type">参数类型</param> 56 /// <param name="arg">参数</param> 57 /// <returns>OBJECT</returns> 58 public static object InvokeConcurrent(string FunName, Type[] type, params object[] arg) 59 { 60 object result = null; 61 Type types = typeof(T); 62 String Key = types.Namespace + "." + types.Name + "." + FunName; 63 String parm_key = ""; 64 try 65 { 66 for (int i = 0; i < type.Length; i++) 67 { 68 parm_key += type[i].Name + "_" + arg[i] + "_"; 69 } 70 Key = Key +":"+ parm_key.TrimEnd('_'); 71 //二级缓存处理 72 if (Cache.GetData(Key) != null) 73 { 74 result = Cache.GetData(Key); 75 } 76 else 77 { 78 Object Odata = Invoke(FunName, type, arg); 79 if (Odata != null) 80 { 81 Cache.Add(Key, Odata, TimeSpan.FromSeconds(1)); 82 } 83 result = Odata; 84 } 85 } 86 catch (Exception ex) 87 { 88 throw ex; 89 } 90 return result; 91 } 92 /// <summary> 93 /// 获取单个类实列 94 /// </summary> 95 /// <returns></returns> 96 public static T GetInstance() 97 { 98 T result = default(T); 99 try 100 { 101 //获得泛型类的对象类型 102 Type type = typeof(T); 103 var classname = type.Namespace + "." + type.Name; 104 if (hash[classname] != null) 105 { 106 result = hash[classname] as T; 107 } 108 else 109 { //根据对象的类型创建对象的实例 110 result = Activator.CreateInstance(type) as T; 111 hash[classname] = result; 112 } 113 } 114 catch (Exception error) 115 { 116 throw error; 117 } 118 return result; 119 } 120 } 121 }