using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using Logs; namespace cuidian.Common { public class ClassFactory { private static ClassFactory __singleton = new ClassFactory(); private Dictionary __assemblyMaps = new Dictionary(); private Dictionary __typeMaps = new Dictionary(); private ClassFactory() { } public static ClassFactory Instance { get { return __singleton; } } public T CreateInstance(string typeName, object[] args) { return __CreateInstance(__GetType(typeName), args); } public T CreateInstance(string typeName) { return __CreateInstance(__GetType(typeName)); } private T __CreateInstance(Type type, object[] args) { object obj; try { obj = Activator.CreateInstance(type, args);//根据类型创建实例 } catch (Exception ex) { LogHelper.Debug("创建类型:" + type.Name + "失败"); throw ex; } return (T)obj; } private T __CreateInstance(Type type) { object obj; try { obj = Activator.CreateInstance(type);//根据类型创建实例 } catch (Exception ex) { LogHelper.Debug("创建类型:" + type.Name + "失败"); throw ex; } return (T)obj; } private Type __GetType(string type) { if (!__typeMaps.ContainsKey(type)) { __AddType(type); } return __typeMaps[type]; } private void __AddType(string typeName) { string[] split = typeName.Split(new string[] { "," }, StringSplitOptions.None); Assembly asm = __GetAssembly(split[0]); Type type = asm.GetType(split[1]); if (type == null) { LogHelper.Debug("加载类型:" + split[1] + "失败"); throw new Exception("加载类型:" + split[1] + "失败"); } __typeMaps.Add(typeName, type); } private Assembly __GetAssembly(string assembly) { if (!__assemblyMaps.ContainsKey(assembly)) { __AddAssembly(assembly); } return __assemblyMaps[assembly]; } private void __AddAssembly(string assembly) { Assembly asm = Assembly.Load(assembly); __assemblyMaps.Add(assembly, asm); } } }