使用反射(Reflect)獲取dll文件中的類型并調(diào)用方法,具體內(nèi)容如下
需引用:System.Reflection;
1. 使用反射(Reflect)獲取dll文件中的類型并調(diào)用方法(入門案例)
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)建該類型的實(shí)例 object obj = Activator.CreateInstance(type); //獲取該類的方法 MethodInfo mf = type.GetMethod("ShowDrives"); //調(diào)用方法 mf.Invoke(obj, null); Console.ReadKey(); }
2. 生成類庫(kù)(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("該電腦的磁盤驅(qū)動(dòng)器有:/r/n"); foreach (var item in drives) { Console.WriteLine(item); } } }}
3. 反射調(diào)用結(jié)果:
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持VEVB武林網(wǎng)。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注