使用反射(Reflect)獲取dll文件中的類型并調用方法,具體內容如下
需引用:System.Reflection;
1. 使用反射(Reflect)獲取dll文件中的類型并調用方法(入門案例)
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"); //創建該類型的實例 object obj = Activator.CreateInstance(type); //獲取該類的方法 MethodInfo mf = type.GetMethod("ShowDrives"); //調用方法 mf.Invoke(obj, null); Console.ReadKey(); }
2. 生成類庫(computer.dll)的computer.cs文件代碼
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("該電腦的磁盤驅動器有:/r/n"); foreach (var item in drives) { Console.WriteLine(item); } } }}
3. 反射調用結果:
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VEVB武林網。
新聞熱點
疑難解答