C#實現反射調用動態載入的DLL檔案中的方法from:http://hi.baidu.com/mkjmmc/blog/item/b5c3192ad2d2de3b5243c141.html
反射的作用:
1. 可以使用反射動態地建立類型的執行個體,將類型綁定到現有對象,或從現有對象中擷取類型
2. 應用程式需要在運行時從某個特定的程式集中載入一個特定的類型,以便實現某個任務時可以用到反射。
3. 反射主要應用與類庫,這些類庫需要知道一個類型的定義,以便提供更多的功能。
1 需要反射的DLL
using System;
namespace Webtest
{
public class ReflectTest
{
public ReflectTest(){}
public string WriteString(string s)
{
return "歡迎您," + s;
}
//靜態函數
public static string WriteName(string s)
{
return "歡迎您光臨," + s;
}
//不帶參數的函數
public string WriteNoPara()
{
return "您使用的是無參數方法";
}
}
}
應用於反射的例子-在ASPNET頁面中加入以下函數:
public void test1()
{
System.Reflection.Assembly ass;
Type type ;
object obj;
try
{
ass = System.Reflection.Assembly.LoadFile(@"d:\TestReflect.dll");//要絕對路徑
type = ass.GetType("Webtest.ReflectTest");//必須使用名稱空間+類名稱
System.Reflection.MethodInfo method = type.GetMethod("WriteString");//方法的名稱
obj = ass.CreateInstance("Webtest.ReflectTest");//必須使用名稱空間+類名稱
string s = (string)method.Invoke(obj,new string[]{"jianglijun"}); //執行個體方法的調用
或:string s = (string)method.Invoke(obj,Object[] parametors = new Object[]{"param"});
Response.Write(s+"<br>");
method = type.GetMethod("WriteName");//方法的名稱
s = (string)method.Invoke(null,new string[]{"jianglijun"}); //靜態方法的調用
Response.Write(s+"<br>");
method = type.GetMethod("WriteNoPara");//無參數的執行個體方法
s = (string)method.Invoke(obj,null);
Response.Write(s+"<br>");
method = null;
}
catch(Exception ex)
{
Response.Write(ex+"<br>");
}
finally
{
ass = null;
type = null;
obj = null;
}
}