• c# 如何进行动态加载dll


      最近遇到了在c#中如何进行动态加载dll的话,搞定了,下面介绍一下自己的步骤。

      1,新建dll。

        打开vs,新建project-》Class Library->项目名为testdll1.在新建的项目中,写入自己的方法,然后运行项目,之后在项目的bin/debug中找到一个      testdll1.dll文件.(一定要运行这个工程,不然在bin/debug里不能生成dll文件)

        

             using System;

             using System.Collections.Generic;

             using System.Linq;

             using System.Text;

             using System.Threading.Tasks;

             namespace testdll1 {

                    public class Class1     {

                             public static long add(long a,long b)  

                               {

                                    return (a*b);

                                }

                 } }

      这样一个简单的dll文件就算完成了。

          2,新建一个工程。

        打开vs,新建project-》Winform->项目名为test。这样一个项目算是建立了。接着就是在项目里动态加载dll了。(这里我是在程序里的AppConfig配置文件直接读的,觉得这个以后修改dll,调用方法的话效率会更高点。)

               

      private void test()
      {
      string path = ConfigurationManager.AppSettings["document"];

      if (!File.Exists(path))
      {
      MessageBox.Show("path is not exist!");
      }
      else
      {
      Assembly ass = Assembly.LoadFrom(ConfigurationManager.AppSettings["document"]); //加载dll文件
      Type tp = ass.GetType(ConfigurationManager.AppSettings["className"]); //获取类名,必须 命名空间+类名
      Object obj = Activator.CreateInstance(tp); //建立实例
      MethodInfo meth = tp.GetMethod(ConfigurationManager.AppSettings["methodName"]); //获取方法
      int t = Convert.ToInt32(meth.Invoke(obj, new Object[] { 4, 3 })); //Invoke调用方法
      }
      }

               3,从AppConfig里读加载文件,获取的类名,以及方法。        

         <appSettings >
          <add key = "document" value = "C:UsersAdministratorDesktop33 est3dll.dll" /> (加载文件的路径+文件)
          <add key = "className" value = "test3dll.Class2" /> (获取的类名)
          <add key = "methodName" value = "add" />  (获取方法)
        </appSettings>

       ok,这就是一个简单的动态加载dll文件的过程了。技术有限,若有更好的方法,求赐教。

  • 相关阅读:
    新东方英语学习方法
    最易遭老板“炒”的15种员工
    如何阅读代码
    Window 消息大全使用详解
    英语学习的六大原则
    单用户多角色权限的MSSQL实现
    .Net中的5种事务总结
    一个.Net程序员关于学习的思考顺带思考人生
    Server 2005中的分区表(一):什么是分区表?为什么要用分区表?如何创建分区表?
    推荐几个win8系统下载比较好的网站
  • 原文地址:https://www.cnblogs.com/qianchunsheng/p/3595294.html
Copyright © 2020-2023  润新知