具體實現參考:
C# 動態加載DLL通過反射調用參數、方法、窗體_c#反射加載dll并傳入參數-CSDN博客
C#進階學習--反射(Reflection) - 知乎
走進C#反射機制 - 知乎
1.使用過程
//創建數據集
Assembly outerAsm = Assembly.LoadFile("D:/your.dll");//獲取調用類型聲明,要把命名空間帶上
Type typeClass = outerAsm.GetType("namespace1.classNameA");//獲取靜態方法聲明
MethodInfo methodStatic = typeClass1.GetMethod("staticFunc");//調用無參靜態方法
object methoVal = methodStatic.Invoke(null, null);//創建實體,有參構造
object obj1 = Activator.CreateInstance(typeClass, new object[]{ para1,para2,...,paraN });//創建實體,無參構造
object obj2 = Activator.CreateInstance(typeClass, null });//獲取非靜態方法聲明
MethodInfo methodGetInit = typeProduct.GetMethod("nonStaticFunc");//調用無參非靜態方法
methodGetInit.Invoke(obj1 , null);//獲取名為Property1的訪問器
PropertyInfo propertyInfo = typeProduct.GetProperty("Property1");聲明//獲取product中名為Property1的訪問器的值
object obj1 = propertyInfo.GetValue(product);
2.loadfrom、loadfile
參考:Assembly.LoadFile 方法 (System.Reflection) | Microsoft Learn
1)loadfrom
加載程序集的時候會連帶性的加載,會連帶把該文件所依賴的dll也加載
2)loadfile
僅加載一個文件,不會連帶把該文件所依賴的dll也加載
3.其他補充
1)當前,在一個AppDomain中只能加載dll,不能卸載,因此在一個AppDomain中不能有同名的dll程序集
2)一個線程屬于一個AppDoMain
參考:C# AppDomain 詳解
3)AssemblyResolve
AssemblyResolve一般配合load方法使用,在load方法找不到程序集的時候,會調用AssemblyResolve解決沖突
AppDomain.CurrentDomain.AssemblyResolve -= OnAssemblyResolve;
List<string> Searchs = new List<string>() {"path1","path2" };
Assembly OnAssemblyResolve(object sender, ResolveEventArgs args)
{var assemblyName = new AssemblyName(args.Name);foreach(var item in Searchs){var file = string.Format("{0}.dll", System.IO.Path.Combine(item, assemblyName.Name));if (File.Exists(file)){return Assembly.LoadFile(file);}}return args.RequestingAssembly;
}
4)常見的沖突
要動態加載的dll跟輸出目錄中的dll沖突了,尤其是調用loadfrom的時候,其所依賴的dll一般會從輸出目錄中獲取,但是輸出目錄中的dll并不是你想要的依賴版本,這時候就會沖突