使用反射(Reflect)獲取dll文件中的類型并調(diào)用方法,具體內(nèi)容如下
需引用:System.Reflection;
1. 使用反射(Reflect)獲取dll文件中的類型并調(diào)用方法(入門案例)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
static void Main( string [] args) { //dll文件路徑 string path = @"D:\VS2015Project\001\Computer\bin\Debug\computer.dll" ; //加載dll文件 Assembly asm = Assembly.LoadFile(path); //獲取類 Type type = asm.GetType( "Computer.Computer" ); //創(chuàng)建該類型的實例 object obj = Activator.CreateInstance(type); //獲取該類的方法 MethodInfo mf = type.GetMethod( "ShowDrives" ); //調(diào)用方法 mf.Invoke(obj, null ); Console.ReadKey(); } |
2. 生成類庫(computer.dll)的computer.cs文件代碼
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace Computer { public class Computer { private DriveInfo[] drives; public Computer() { this .drives = DriveInfo.GetDrives(); } public void ShowDrives() { Console.WriteLine( "該電腦的磁盤驅(qū)動器有:\r\n" ); foreach (var item in drives) { Console.WriteLine(item); } } } } |
3. 反射調(diào)用結(jié)果:
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://www.cnblogs.com/ChengWenHao/archive/2018/10/18/Reflect.html