C# -- 使用反射(Reflect)獲取dll文件中的類型並調用方法


使用反射(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. 反射調用結果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM