文章目錄
- 主要用途:
- Dll
- 使用反射建立Dll中的類執行個體並調用方法
- 完整的代碼
在.Net 中,程式集(Assembly)中儲存了中繼資料(MetaData)資訊,因此就可以通過分析中繼資料來擷取程式集中的內容,比如類,方法,屬性等,這大大方便了在運行時去動態建立執行個體。
MSDN解釋如下:
反射提供了封裝程式集、模組和類型的對象(Type 類型)。可以使用反射動態建立類型的執行個體,將類型綁定到現有對象,或從現有對象擷取類型並調用其方法或訪問其欄位和屬性。如果代碼中使用了屬性,可以利用反射對它們進行訪問。
主要用途:
- 動態載入DLL,實現外掛程式機制。
- 執行個體化DLL中的類型。
- 執行後期綁定,訪問在運行時建立的類型的方法。
今天我就介紹下後面的兩個用途,其實最初的目的只是想根據設定檔中的值建立對應對象。
Dll
先上一段代碼,這是要調用的ClassGreenerycn類,它被編譯為DllDemo.dll。
using System;namespace DllDemo{ public class ClassGreenerycn { public string Name { get; set; } public bool IsTest { get; set; } public void Hello() { Console.WriteLine(Name); } }}
很簡單的代碼,就是一個類中有兩個屬性,Hello方法會向命令列中輸出Name的名稱。
使用反射建立Dll中的類執行個體並調用方法
現在再建立一個命令列的工程,該工程就一個用途,動態載入DllDemo.dll,然後執行個體化一個Name為Greenerycn,IsTest為True的對象,並調用Hello方法。
詳細步驟如下:
1.引用反射的命名空間:
using System.Reflection;
2.動態載入Dll
動態載入Dll有3個函數:
public static Assembly Load(string assemblyString);
- 該方法傳入的是Dll的名字,該Dll必須位於全域緩衝GAC中才行,不然會報“System.IO.FileLoadException: 未能負載檔案或程式集”的異常。
public static Assembly LoadFile(string path);
- 這個LoadFile最方便,參數就是dll的路徑。
public static Assembly LoadFrom(string assemblyFile);
3.擷取ClassGreenerycn類的類型
var type = asm.GetType("DllDemo.ClassGreenerycn");
注意,這裡需要完整的類型名稱,包括簽名的命名空間。
4.建立該類型的執行個體
var instance = asm.CreateInstance("DllDemo.ClassGreenerycn");
5.設定屬性
type.GetProperty("Name").SetValue(instance, "http://greenerycn.cnblogs.com", null);type.GetProperty("IsTest").SetValue(instance, true, null);
6.擷取Hello方法
var method = type.GetMethod("Hello");
7.調用Hello方法
method.Invoke(instance, null);
8.編譯運行
完整的代碼
using System.Reflection;namespace ReflectionDllDemo{ class Program { static void Main(string[] args) { var asm = Assembly.LoadFile(@"d:\3_code\DotNet\DllDemo\DllDemo\bin\Debug\DllDemo.dll"); var type = asm.GetType("DllDemo.ClassGreenerycn"); var instance = asm.CreateInstance("DllDemo.ClassGreenerycn"); type.GetProperty("Name").SetValue(instance, "http://greenerycn.cnblogs.com", null); type.GetProperty("IsTest").SetValue(instance, true, null); var method = type.GetMethod("Hello"); method.Invoke(instance, null); } }}
參考資料:
反射(C# 編程指南)