using System.Collections; using System.Reflection; using VberZero.Tools.StringModel; namespace VberZero.Tools.AssemblyHelpers; public static class AssemblyHelper { public static Type? GetType(string typeName) { Assembly? loadedAssembly = GetLoadedAssembly(typeName); var type = loadedAssembly?.GetType(typeName, false, true); return type; } public static Assembly? GetLoadedAssembly(string typeName) { Assembly? assembly1 = null; foreach (Assembly? assembly2 in AppDomain.CurrentDomain.GetAssemblies()) { if (assembly2.GetType(typeName) != null) { assembly1 = assembly2; break; } } return assembly1; } /// /// 创建实例 /// /// 类名 /// 程序集名 /// public static object? CreateInstance(string typeName, string? lib) { object? obj = null; if (typeName != "") { try { lib = lib.UAndT().Ew(".DLL"); Assembly? assembly = GetLoadedAssembly(typeName) ?? LoadAssembly(lib); obj = assembly?.CreateInstance(typeName); } catch (Exception ex) { if (ex.InnerException != null) throw ex.InnerException; } } return obj; } /// /// 创建实例 /// /// "程序集名"@"类名" /// public static object? CreateInstance(string typeName) { object? obj = null; Array arrayEx = typeName.StrToArray("@"); if (arrayEx.Length >= 2) { string lib = arrayEx.GetValue(0) + ".DLL"; obj = CreateInstance(arrayEx.GetValue(1) + "", lib); } return obj; } public static bool IsInterfaceOf(object obj, string @interface) { return obj.GetType().GetInterface(@interface, true) != null; } public static Assembly? LoadAssembly(string? lib) { Assembly? assembly = null; string fullPathFileName = GetFullPathFileName(lib); if (fullPathFileName != "") { try { assembly = Assembly.LoadFrom(fullPathFileName); } catch (Exception ex) { string message = ex.Message; Console.WriteLine(message); } } return assembly; } public static ArrayList GetSubClassesOf(Type poBaseType, string libs) { ArrayList arrayList = new ArrayList(); foreach (string? lib in libs.StrToArray()) { Assembly? assembly = LoadAssembly(lib); if (assembly != null) { foreach (Type type in assembly.GetTypes()) { bool flag = true; if (poBaseType != null) { if (poBaseType.IsInterface) { if (type.GetInterface(poBaseType.ToString(), true) == null) flag = false; } else if (!type.IsSubclassOf(poBaseType)) flag = false; } if (flag) arrayList.Add(type.FullName); } } } return arrayList; } private static string GetFullPathFileName(string? libs) { string str = $"{AppDomain.CurrentDomain.BaseDirectory}\\{libs}"; return str; } }