博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C#实现反射调用动态加载的DLL文件中的方法
阅读量:4641 次
发布时间:2019-06-09

本文共 1425 字,大约阅读时间需要 4 分钟。

反射的作用:

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 "您使用的是无参数方法";
}
}
}
应用于反射的例子-在NET页面中加入以下函数:
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

你可能感兴趣的文章
python 文件的定位读写
查看>>
模拟浏览器的滚动条,自己拿去美化
查看>>
Music in Car
查看>>
偶记:mysql5.7的官方doc也有错误啊:写的是vc runtime 2010,但实际上必须是 vc runtime 2013。坑...
查看>>
费马小定理,欧拉定理,指数循环节
查看>>
数据类型以的相互转化及赋值操作符,常用数学函数
查看>>
React-Redux之API
查看>>
bzoj千题计划266:bzoj4872: [六省联考2017]分手是祝愿
查看>>
How to prevent XXE attack ( XmlDocument in .net)
查看>>
IP,路由,交换基础培训记录
查看>>
sdut-1118 C语言实验——从大到小输出a、b、c(选择结构)
查看>>
鼠标响应事件
查看>>
使用 install.packages() 安装所需的包
查看>>
matlab 工具函数 —— normalize(归一化数据)
查看>>
狄拉克函数(Dirac delta function)
查看>>
经典书单 —— 语言/算法/机器学习/深度学习/AI/CV/PGM
查看>>
计算积分的方法 —— 分布积分
查看>>
OpenCV——Perlin Noise
查看>>
OpenCV——PS 滤镜, 曝光过度
查看>>
WDA基础十六:ALV的颜色
查看>>