咖啡真苦,蜜糖好甜
认认真真做事,踏踏实实写代码。。。

导航

 

  最近遇到了在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:\Users\Administrator\Desktop\33\test3dll.dll" /> (加载文件的路径+文件)
      <add key = "className" value = "test3dll.Class2" /> (获取的类名)
      <add key = "methodName" value = "add" />  (获取方法)
    </appSettings>

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

posted on 2014-03-12 13:29  咖啡真苦,蜜糖好甜  阅读(1290)  评论(0编辑  收藏  举报