zoukankan
html css js c++ java
利用反射动态调用类成员[原创]
1
.首先建立一个类
class
PropertyClass
{
public
PropertyClass()
{
}
public
PropertyClass(
ref
Int32 x)
{
x
*=
5
;
}
public
int
fieldValue
=
0
;
private
string
name;
public
string
Name
{
get
{
return
name; }
set
{ name
=
value; }
}
public
int
GetInt(
int
value)
{
return
value;
}
public
void
Display(
string
str)
{
Console.WriteLine(str);
}
public
override
String ToString()
{
return
fieldValue.ToString();
}
}
2
.用反射的方式调用这个PropertyClass类中的方法
public
static
void
instanceLove()
{
PropertyClass propertyClass
=
new
PropertyClass();
Type type
=
propertyClass.GetType();
//
Type type = typeof(propertyClass);效果和上面语句一样,只是写法不同。
object
obj
=
type.InvokeMember(
null
, BindingFlags.DeclaredOnly
|
BindingFlags.Public
|
BindingFlags.NonPublic
|
BindingFlags.Instance
|
BindingFlags.CreateInstance,
null
,
null
,
new
object
[]
{ }
);
//
调用没有返回值的方法
//
运行之后的结果[Hello World]
type.InvokeMember(
"
Display
"
, BindingFlags.InvokeMethod
|
BindingFlags.Public
|
BindingFlags.Instance,
null
, obj,
new
object
[]
{
"
Hello World
"
}
);
//
调用有返回值的方法
//
运行之后的结果[1982]
int
i
=
(
int
)type.InvokeMember(
"
GetInt
"
, BindingFlags.InvokeMethod
|
BindingFlags.Public
|
BindingFlags.Instance,
null
, obj,
new
object
[]
{
1982
}
);
//
设置属性值
//
此时的Name 's Value为[My Name is Brian Lei]
type.InvokeMember(
"
Name
"
, BindingFlags.SetProperty,
null
, obj,
new
object
[]
{
"
My Name is Brian Lei
"
}
);
//
获取属性值
//
运行之后的结果[My Name is Brian Lei]
string
str
=
(
string
)type.InvokeMember(
"
Name
"
, BindingFlags.GetProperty,
null
, obj,
null
);
//
设置字段值
type.InvokeMember(
"
fieldValue
"
, BindingFlags.SetField,
null
, obj,
new
object
[]
{
813
}
);
//
获取字段值
//
运行之后的结果[813]
int
f
=
(
int
)type.InvokeMember(
"
fieldValue
"
, BindingFlags.GetField,
null
, obj,
null
);
//
调用override方法
//
运行之后的结果[813]
String s
=
(String)type.InvokeMember(
"
ToString
"
, BindingFlags.DeclaredOnly
|
BindingFlags.Public
|
BindingFlags.NonPublic
|
BindingFlags.Instance
|
BindingFlags.InvokeMethod,
null
, obj,
null
);
//
调用构造方法
//
运行之后的结果[8*5=40]
Object objs
=
type.InvokeMember(
null
,BindingFlags.DeclaredOnly
|
BindingFlags.Public
|
BindingFlags.NonPublic
|
BindingFlags.Instance
|
BindingFlags.CreateInstance,
null
,
null
,
new
Object[]
{
8
}
);
}
3
.写个Main函数测试一下
class
EntryPoint
{
static
void
Main()
{
Test.instanceLove();
}
}
查看全文
相关阅读:
响应式设计
小视频-上传视频
美多商城项目总结
jwt 接口加密
flask入门小方法
flask的继承和包含
flask中的宏
flask的jinja2模板中过过滤器的相关小内容
flask中的简单的前端写入
flask的cookie和session的简单原理
原文地址:https://www.cnblogs.com/RuiLei/p/674833.html
最新文章
序
CVPR2018+ECCV2018目标检测算法汇总
经典目标检测框架的要点总结
vot数据集使用方法(工具包)
2017阿里C++研发工程师-校招-单词匹配
2017阿里C++研发工程师-校招-笔试模拟
链家网-后台开发工程师笔试题-第三题
猜数字游戏-牛客三模题目
单向链表转平衡二叉搜索树
矩阵中的路径
热门文章
链表中环的入口结点
多线程客户端-服务器模型
IO多路复用客户端-服务器模型
多进程客户端-服务器模型
集群和分布式
面向对象的简单理解以及代码
redis的技术点
部署前端
在一对多和多对多中使用ORM
云服务部署
Copyright © 2011-2022 走看看