zoukankan
html css js c++ java
一个浅显易懂的反射例子
反射,就是程序集的一面镜子,所以才叫反射.废话少说,以一个简单的例子切入正题吧:
1 创建用于反射使用的DLL
新建一个C#类库项目,拷贝源代码如下,编译生成DLL(假如DLL的文件名是TestReflect.dll)
代码如下:
using
System;
namespace
Webtest
{
/**/
///
<summary>
///
Summary description for ReflectTest.
///
</summary>
public
class
ReflectTest
{
public
ReflectTest()
{
//
//
TODO: Add constructor logic here
//
}
public
string
WriteString(
string
s)
{
return
"
欢迎您,
"
+
s;
}
/**/
/**/
/**/
///
<summary>
///
dsajkjflasjdfalksdjfaskfd
///
</summary>
///
<param name="s"></param>
///
<returns></returns>
public
static
string
WriteName(
string
s)
{
return
"
欢迎您光临,
"
+
s;
}
public
string
WriteNoPara()
{
return
"
您使用的是无参数方法
"
;
}
}
}
应用于反射的例子
在ASPNET页面中加入以下函数:
private
void
Button1_Click(
object
sender, System.EventArgs e)
{
System.Reflection.Assembly ass;
Type type ;
object
obj;
try
{
ass
=
System.Reflection.Assembly.LoadFile(
@"
C:\TestReflect\ReflectQuickStart\TestReflect\bin\Debug\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
"
}
);
//
实例方法的调用
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
;
}
}
以上是本人的粗浅理解,但是倒是可以作为一个入门的例子.just keep it simple and stupid.
查看全文
相关阅读:
LTE第一章 介绍
一本关于 LTE 非常好的书籍
Memcached安装卸载
很好很实用的.net、网站系统后台模板
MS SQL 当记录不存在时插入insert INTO not exists
数据库存储过程缺点总结
存储过程是罪恶
树形数据查询示例
安装Discuz!论坛时提示“mysqli_connect() 不支持 advice_mysqli_connect”
sql server中将一个表中的部分数据插入到另一个表中
原文地址:https://www.cnblogs.com/engine1984/p/1032078.html
最新文章
Yii中的relations方法
Yii自定义验证规则
Yii 验证和消息
LSF作业管理系统使用方法
Yii中POS和GET并用范例
perl学习---控制:unless,until,next,redo,last
__call、__set 和 __get的用法
MySQL常用函数 一
php foreach用法和实例
AJAX 跨域请求
热门文章
没有特别幸运
【转】2013 PHP技术峰会《Bug Free的PHP开发实践分享》摘录
第二篇:zc706 基本外设及usb DEVICE模式测试过程
第一篇:zc706 开箱及开发环境搭建
python数据类型(一)
python运算符
Python变量
Python中的文件类型
centos6.5下安装python3安装、python3虚拟环境创建venv
ubuntu16.04下安装opencv3.2版本
Copyright © 2011-2022 走看看