C#實現反射調用動態加載的DLL文件中的方法

摘自:http://www.knowsky.com/539917.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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章