在VS2010中创建并引用dll(C#)

 一般情况下,如果在新建或添加时选择“windows应用程序”或“控制台应用程序”时,‎结果都会被编译成exe,而选择“类库”时就会被编译成dll。也可以在项目属性中更改其输出类型,如下图:


        下面上一个创建dll并引用的实例.
        1.新建一个项目,选择类库,命名DllTest。然后写一个类,里面包含一些方法什么的,为了突出主题,作为例子,我就写了一个简单的类,如下:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. namespace DllTest
  6. {
  7. // 求两个数或三个数的最大值
  8. public static class TestClass
  9. {
  10. public static int GetMax(int a, int b)
  11. {
  12. return (a > b ? a : b);
  13. }
  14. public static int GetMax(int a, int b, int c)
  15. {
  16. return ((a > b ? a : b) > c ? (a > b ? a : b) : c);
  17. }
  18. }
  19. }

        点“生成”后在 bin\debug 文件夹下会出现一个与项目名同名的dll文件

        2.再新建一个项目(也可以建一个新的解决方案)命名DllRef这时就不要选类库类型了,Win应用和Console任选一个,然后添加对刚刚生成的dll文件的引用,并using其命名空间。

 

        这时在本项目的bin\Debug文件夹下也出现了一个dll文件,就是我们引用的那个。
       写相关调用语句:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using DllTest;
  6. namespace DllRef
  7. {
  8. class Program
  9. {
  10. static void Main(string[] args)
  11. {
  12. Console.WriteLine(TestClass.GetMax(5, 6));
  13. Console.WriteLine(TestClass.GetMax(7, 8, 9));
  14. }
  15. }
  16. }

      将第二个项目设为启动项,试运行成功。就是说我们在新的项目中,用到了封装在dll中的类。
       dll为一个程序集,可以被不同的程序重复调用,只要将其成功引用并using其命名空间即可。












posted @ 2016-03-21 13:43  Hank_Yan  阅读(746)  评论(0编辑  收藏  举报