123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117 |
- 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<string, Assembly> __assemblyMaps = new Dictionary<string, Assembly>();
- private Dictionary<string, Type> __typeMaps = new Dictionary<string, Type>();
- private ClassFactory()
- { }
- public static ClassFactory Instance
- {
- get { return __singleton; }
- }
- public T CreateInstance<T>(string typeName, object[] args)
- {
- return __CreateInstance<T>(__GetType(typeName), args);
- }
- public T CreateInstance<T>(string typeName)
- {
- return __CreateInstance<T>(__GetType(typeName));
- }
- private T __CreateInstance<T>(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<T>(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);
- }
- }
- }
|