使用反射(Reflect)獲取dll文件中的類型並調用方法
需引用:System.Reflection;
1. 使用反射(Reflect)獲取dll文件中的類型並調用方法(入門案例)
1 static void Main(string[] args) 2 { 3 //dll文件路徑 4 string path = @"D:\VS2015Project\001\Computer\bin\Debug\computer.dll"; 5 6 //加載dll文件 7 Assembly asm = Assembly.LoadFile(path); 8 9 //獲取類 10 Type type = asm.GetType("Computer.Computer"); 11 12 //創建該類型的實例 13 object obj = Activator.CreateInstance(type); 14 15 //獲取該類的方法 16 MethodInfo mf = type.GetMethod("ShowDrives"); 17 18 //調用方法 19 mf.Invoke(obj, null); 20 21 Console.ReadKey(); 22 }
2. 生成類庫(computer.dll)的computer.cs文件代碼
1 using System; 2 using System.Collections.Generic; 3 using System.IO; 4 using System.Linq; 5 using System.Text; 6 7 8 namespace Computer 9 { 10 public class Computer 11 { 12 private DriveInfo[] drives; 13 public Computer() 14 { 15 this.drives = DriveInfo.GetDrives(); 16 } 17 public void ShowDrives() 18 { 19 Console.WriteLine("該電腦的磁盤驅動器有:\r\n"); 20 foreach (var item in drives) 21 { 22 Console.WriteLine(item); 23 } 24 } 25 } 26 }
3. 反射調用結果: