架构师_程序员_码农网

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 11611|回复: 1

[资料] C#动态态引用DLL的方法(转载)

[复制链接]
发表于 2015-2-5 20:54:58 | 显示全部楼层 |阅读模式
首先,我们需要封装一个dll,vs2008下建立一个类库,代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using 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); 就行了。

System.Text;
namespace dll
{
    public class addclass
    {
        public static Int32 add(Int32 i, Int32 j)
        {
            return i + j;
        }
    }
}




上一篇:如何在C#中调用C/C++ DLL中的方法
下一篇:MySQL忘记密码恢复密码的实现方法
码农网,只发表在实践过程中,遇到的技术难题,不误导他人。
发表于 2018-3-19 21:31:01 | 显示全部楼层
net环境下开发的Dll库没有VC6的通用性强
码农网,只发表在实践过程中,遇到的技术难题,不误导他人。
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则

免责声明:
码农网所发布的一切软件、编程资料或者文章仅限用于学习和研究目的;不得将上述内容用于商业或者非法用途,否则,一切后果请用户自负。本站信息来自网络,版权争议与本站无关。您必须在下载后的24个小时之内,从您的电脑中彻底删除上述内容。如果您喜欢该程序,请支持正版软件,购买注册,得到更好的正版服务。如有侵权请邮件与我们联系处理。

Mail To:help@itsvse.com

QQ|手机版|小黑屋|架构师 ( 鲁ICP备14021824号-2 )|网站地图

GMT+8, 2024-5-2 00:30

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表