反射的作用:
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;
}
}
--------------------------------------------------------------------------------
具體應用:
假設另一個工程中的所有類都編譯到一個dll檔案中了,在這很多的類當中,有一個類叫StringUtil,名稱空間在HSMP.CommonBasic.Common下
該類中有一個方法:
public double GetSum(double x,double y)
{
return x+y;
}
編譯後dll檔案的存放路徑是:D:\Test\HSMP.CommonBasic.dll
現在的問題是,如何通過程式調用該dll檔案中的GetSum方法
大概有以下幾步:
using System.Reflection;
A.
//這裡要用LoadFrom,只有在本工程裡添加了該dll的引用後才可以使用Load
Assembly objAss = Assembly.LoadFrom(@"D:\Test\HSMP.CommonBasic.dll");
//HSMP.CommonBasic.Common.StringUtil類的全路徑
Type t=objAss.GetType("HSMP.CommonBasic.Common.StringUtil");
//動態產生類StringUtil的執行個體
object obj=System.Activator.CreateInstance(t);
//參數資訊,GetSum需要兩個int參數,如果方法沒有參數,就聲明一個長度為0的數組
System.Type[] paramTypes = new System.Type[2];
paramTypes[0] = System.Type.GetType("System.Int32");
paramTypes[1] = System.Type.GetType("System.Int32");
//找到對應的方法
MethodInfo p = t.GetMethod("GetSum", paramTypes)
//參數值,如果所調用的方法沒有參數,不用寫這些
Object[] parameters = new Object[2];
parameters[0] = 3;
parameters[1] = 4;
object objRetval = p.Invoke(obj, parameters); //如果沒有參數,寫null即可。