zoukankan
html css js c++ java
C#如何动态调用DLL中类的方法以及属性
在C#中可以通过Assembly来动态加载DLL,然后由它创建类型,接着通过类型的InvokeMember方法来调用DLL中类的方法以及属性。
为了方便说明一下的方法,先说明一下DLL的代码,大致如下:
using
System;
namespace
clsTestDll
{
/**/
///
<summary>
///
Summary description for TestDll.
///
</summary>
public
class
TestDll
{
private
string
strName;
public
TestDll()
{
//
//
TODO: Add constructor logic here
//
strName
=
""
;
}
public
string
GetValue(
int
nCount )
{
return
string
.Format(
"
Count is {0}!
"
, nCount );
}
public
static
string
GetNewValue(
int
nCount )
{
return
string
.Format(
"
New count is {0}!
"
, nCount );
}
public
string
Name
{
get
{
return
strName;}
set
{ strName
=
value;}
}
}
}
大致的步骤如下:
首先加载DLL,具体如下:
//
Load assembly from dll file
Assembly assembly
=
Assembly.LoadFrom(
"
clsTestDll.dll
"
);
其次,用加载的assembly来定义指定的类型,例如:
//
Create new type
Type t
=
assembly.GetType(
"
clsTestDll.TestDll
"
);
然后就可以通过新建的类型来调用类的方法。
如果是类的静态方法,可以直接调用,如:
//
Call static member function by name
string
strReturn
=
(
string
) t.InvokeMember(
"
GetNewValue
"
,
BindingFlags.DeclaredOnly
|
BindingFlags.Public
|
BindingFlags.Static
|
BindingFlags.InvokeMethod,
null
,
null
,
new
object
[]
{
12
}
);
如果是类的非静态方法或属性,则需要通过类型,先生成类的对象,如:
//
Create new object of specific class name
Object obj
=
t.InvokeMember(
null
,
BindingFlags.DeclaredOnly
|
BindingFlags.Public
|
BindingFlags.NonPublic
|
BindingFlags.Instance
|
BindingFlags.CreateInstance,
null
,
null
,
null
);
接着,就可以通过“obj”对象来进行调用了,如:
//
Call member function by name
strReturn
=
(
string
) t.InvokeMember(
"
GetValue
"
,
BindingFlags.DeclaredOnly
|
BindingFlags.Public
|
BindingFlags.NonPublic
|
BindingFlags.Instance
|
BindingFlags.InvokeMethod,
null
,
obj,
new
object
[]
{
12
}
);
//
Set class property
t.InvokeMember(
"
Name
"
,
BindingFlags.DeclaredOnly
|
BindingFlags.Public
|
BindingFlags.NonPublic
|
BindingFlags.Instance
|
BindingFlags.SetProperty,
null
,
obj,
new
Object[]
{
"
Test
"
}
);
//
Get class property
strReturn
=
(
string
) t.InvokeMember(
"
Name
"
,
BindingFlags.DeclaredOnly
|
BindingFlags.Public
|
BindingFlags.NonPublic
|
BindingFlags.Instance
|
BindingFlags.GetProperty,
null
,
obj,
null
);
查看全文
相关阅读:
第8月第15天 app支持后台播放
第8月第12天 python json.dumps danmu
第7月第27天 c++11 boost
第7月第26天 iOS httpserver
第7月第25天 xcode bundle calayer动画
我曾七次鄙视自己的灵魂
learning shell display alert function(5)
learning armbian steps(6) ----- armbian 源码分析(一)
learning scala 数组和容器
learning scala ide tools install
原文地址:https://www.cnblogs.com/pricks/p/1601827.html
最新文章
赋值运算符重载
运算符小括号重载
下标运算符重载
Linux之信号
kill函数
sql server 分组,取每组的前几行数据
forfiles删除过期文件robocopy
共享路径
SQL Server 2016新特性: 对JSON的支持
SQL Server 2012 手动安装帮助文档+排错
热门文章
关于论文格式要求及字体大小
SQL 事务隔离级别
Sql Server 按格式输出日期
网络资源
SQL Server将一列的多行内容拼接成一行
第9月第3天 uilabel contentscale
第8月第22天 python scrapy
第8月第21天 django lbforum项目记录
第8月第19天 django rest
第8月第16天 django pil
Copyright © 2011-2022 走看看