[c#美味] 使用反射動態建立執行個體並調用方法

來源:互聯網
上載者:User
文章目錄
  • 主要用途:
  • Dll
  • 使用反射建立Dll中的類執行個體並調用方法
  • 完整的代碼

在.Net 中,程式集(Assembly)中儲存了中繼資料(MetaData)資訊,因此就可以通過分析中繼資料來擷取程式集中的內容,比如類,方法,屬性等,這大大方便了在運行時去動態建立執行個體。

MSDN解釋如下:

反射提供了封裝程式集、模組和類型的對象(Type 類型)。可以使用反射動態建立類型的執行個體,將類型綁定到現有對象,或從現有對象擷取類型並調用其方法或訪問其欄位和屬性。如果代碼中使用了屬性,可以利用反射對它們進行訪問。

主要用途:
  1. 動態載入DLL,實現外掛程式機制。
  2. 執行個體化DLL中的類型。
  3. 執行後期綁定,訪問在運行時建立的類型的方法。

 

今天我就介紹下後面的兩個用途,其實最初的目的只是想根據設定檔中的值建立對應對象。

 

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);
  • 這個方法也可以,參數同樣是dll路徑。

 

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# 編程指南)

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.