如何动态调用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);