您的位置:首页 > 编程语言 > C#

C#动态引用DLL的方法

2012-11-25 11:27 274 查看
http://csidm.com

C#编程中,使用dll调用是经常的事,这样做的好处是非常多的,比如把某些功能封装到一个dll中,然后主程序动态调用这个dll。

废话不多说,举例说明如下。

首先,我们需要封装一个dll,vs2008下建立一个类库,代码如下:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace dll

{

public class addclass

{

public static Int32 add(Int32 i, Int32 j)

{

return i + j;

}

}

}

编译生成 dll.dll ,其中 类名是 addclass, 方法是 add 。

接下来在主程序中调用 这个 dll.dll ,需要先把这个 dll.dll 复制到主程序的 bin\Debug 文件夹下。 动态引用 dll 需要用到 using System.Reflection; 这个反射命名空间。

private void test()

{

Assembly ass = Assembly.Load("dll"); //加载dll文件

Type tp = ass.GetType("dll.addclass"); //获取类名,必须 命名空间+类名

Object obj = Activator.CreateInstance(tp); //建立实例

MethodInfo meth = tp.GetMethod("add"); //获取方法

int t = Convert.ToInt32( meth.Invoke(obj, new Object[]{2, 3}) ); //Invoke调用方法

MessageBox.Show(t.ToString());

}

上面介绍的是动态调用 dll 的方法,你也可以通过 引用 --> 添加引用(dll.dll)的方法进行前期加载,并配合 using dll的命名空间名称; 来使用。主程序中直接用 int t= addclass.add(2, 3); 就行了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: