假设已有组件ClassLibraryTEST.dll,放置于程序目录下。组件中ClassLibraryTEST命名空间下有TEST类,类中有方法sum。下面示例就是动态加载组件并调用sum方法的简例:
static void Main(string[] args)
{
string dllPath = string.Format("{0}\\ClassLibraryTEST.dll", System.Environment.CurrentDirectory);//dll组件路径
Assembly pAss = Assembly.LoadFile(dllPath);//加载组件
Type pType = pAss.GetType("ClassLibraryTEST.TEST");//获得类,ClassLibraryTEST命名空间,TEST类名
MethodInfo pMtInfo = pType.GetMethod("sum");//获得方法,sum方法名
object o = Activator.CreateInstance(pType);//创建类实例
int sum = (int)pMtInfo.Invoke(o, new object[] { , });//调用方法
}
下面是组件代码:
namespace ClassLibraryTEST
{
public class TEST
{
private int a = ;
private int b = ;
public string s = "n";
private int Add(int a,int b)
{
return a + b;
}
public int sum(int a, int b)
{
return a + b;
}
private string url = "www.123.com";
}
}