在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);
新闻热点
疑难解答