C#实现反射调用动态加载的DLL文件中的方法
反射的作用:
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;
}
}?
轉載于:https://www.cnblogs.com/kennyliu/p/3584478.html
總結
以上是生活随笔為你收集整理的C#实现反射调用动态加载的DLL文件中的方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 服务器端Session和客户端Sessi
- 下一篇: C#反射——简单反射操作类的封装