C#反射 程序域
1:加载dll到当前应用程序域:
public static void LoadAllAssembly(string bindir) //bindir是dll所在的完整路径 { List<Assembly> _lst = new List<Assembly>(AppDomain.CurrentDomain.GetAssemblies()); List<string> filelist = new List<string>(System.IO.Directory.GetFiles(bindir, "*.dll")); //filelist.AddRange(System.IO.Directory.GetFiles(bindir, "*.exe")); //如果需要也加载exe的话,取消注释 for (int i = 0; i < filelist.Count; i++) { string f = filelist[i]; f = Path.GetFileName(f).ToLower(); if (f.StartsWith("interop.") || f.Contains(".vshost.exe")) continue; if (!f.EndsWith(".dll") && !f.EndsWith(".exe")) continue; try { if (!CheckAssemblyLoaded(_lst, filelist[i])) _lst.Add(Assembly.LoadFrom(filelist[i])); } catch (Exception ex) { Console.WriteLine("[" + DateTime.Now.ToShortTimeString() + "] " + ex.Message); //ErrorMessage.ErrorMessage.Show(ex); } } } private static bool CheckAssemblyLoaded(List<Assembly> list, string filename) { if (string.IsNullOrEmpty(filename) || list == null || list.Count == 0) return false; try { filename = filename.ToLower(); for (int i = 0; i < list.Count; i++) { if (Path.GetFileName(list[i].Location).ToLower() == filename) return true; } } catch (Exception ex) { Console.WriteLine("[" + DateTime.Now.ToShortTimeString() + "] " + ex.Message); return false; } return false; }
2:根据类的全名遍历所有appdomain中的程序集,取得相应的类型
private static Dictionary<string, Type> _typeList = new Dictionary<string, Type>(); /// <summary> /// 根据类的全面获取类型,将在当前AppDomain中的所有加载的程序集中查找 /// </summary> /// <param name="fullname">类型的Fullname</param> /// <returns>类型,若不存在返回null</returns> public static Type GetType(string fullname) { if (fullname == null) return null; if (_typeList.ContainsKey(fullname)) return _typeList[fullname]; if (!string.IsNullOrEmpty(fullname)) { Assembly[] a = AppDomain.CurrentDomain.GetAssemblies(); for (int i = 0; i < a.Length; i++) { Type t = a[i].GetType(fullname); if (t != null) { _typeList.Add(fullname, t); return t; } } } return null; }