zoukankan
html css js c++ java
利用反射动态调用类成员(泛型篇)
1
.泛型类: 通过这个类中的invokeMethod动态调用InvokeClass中的method.
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
public
sealed
class
DynamicLoadMethod
<
T
>
where T :
class
{
private
static
object
obj
=
new
object
();
private
static
T invokeMethod;
public
static
T InvokeMethod
{
get
{
lock
(obj)
{
if
(invokeMethod
==
null
)
{
invokeMethod
=
typeof
(T).InvokeMember(
typeof
(T).Name, BindingFlags.CreateInstance
|
BindingFlags.Instance
|
BindingFlags.NonPublic
|
BindingFlags.Public,
null
,
null
,
null
,
null
)
as
T;
}
return
invokeMethod;
}
}
}
}
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
2
.被动态调用的方法Class
public
class
InvokeClass
{
private
String Name;
public
String Names
{
set
{ Name
=
value; }
}
public
override
string
ToString()
{
return
Name;
}
private
Object[] values
=
new
Object[]
{
0
,
1
,
2
,
3
,
4
,
5
,
6
,
7
,
8
,
9
}
;
public
Object
this
[
int
index]
{
get
{
return
values[index];
}
set
{
values[index]
=
value;
}
}
public
Object Value
{
get
{
return
"
the value
"
;
}
}
public
InvokeClass()
{
Name
=
"
initialName
"
;
}
int
methodCalled
=
0
;
public
void
AddUp()
{
methodCalled
++
;
Console.WriteLine(
"
AddUp Called {0} times
"
, methodCalled);
}
public
void
PrintTime()
{
Console.WriteLine(DateTime.Now);
}
public
void
Swap(
ref
int
a,
ref
int
b)
{
int
x
=
a;
a
=
b;
b
=
x;
}
}
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
3
.调用方法
static
void
Main(
string
[] args)
{
Console.WriteLine(DynamicLoadMethod
<
InvokeClass
>
.InvokeMethod.Value
as
String);
DynamicLoadMethod
<
InvokeClass
>
.InvokeMethod.AddUp();
DynamicLoadMethod
<
InvokeClass
>
.InvokeMethod.Names
=
"
BrianLei Build
"
;
Console.WriteLine(DynamicLoadMethod
<
InvokeClass
>
.InvokeMethod.ToString());
}
最后的话,简单测试了一下,Loop100百万次,
直接调用方法,只花了20毫秒,
而动态调用方法的话,花了12秒
所以大家知道怎么这个思路,就可以了。
在web form 中最好不要使用。
在win form还是可以小试的。
查看全文
相关阅读:
使用正向proxy 连调部署在k8s 中的spring cloud 中的rest服务
goflow golang 的基于flow的编程库
gvm golang 的多版本工具
jvm-profiler 学习试用
httpdiff http 请求diff 工具
tengine lua 模块docker 镜像集成
tengine 支持dubbo 的docker镜像
openresty ngx.location.capture http2 问题
systemd 使用rc.local 说明
revel golang的全栈开发框架
原文地址:https://www.cnblogs.com/RuiLei/p/676182.html
最新文章
C# WinForm捕获全局异常
axios不支持finally的解决办法
npm -i 与npm install -S与-D的区别以及dependencies与devDependencies的区别
axios POST提交数据的三种请求方式写法
在Vue使用NProgress加载进度条
理解@app.route()
Python random 库 Cheatsheet
Python Tornado入门
SecureCRT 8.5 绿色免安装(亲测诺顿杀毒通过)及sftp的用法
mormot对windows websocket的封装
热门文章
mormot对http.sys的封装
TFDQuery提交TFDMemTable修改的数据
TFDMemTable已修改的数据序列为流
firedac数据集序列为流
流接口
firedac接口
olevariant接口
TRestClient
中间件集群协议msgpack
几个不错的golang proxy包
Copyright © 2011-2022 走看看