C#中的DLL文件

来源:互联网 发布:苹果怎么授权给软件 编辑:程序博客网 时间:2024/06/07 10:25

百度百科

  DLL(Dynamic Link Library)文件为动态链接库文件,又称“应用程序拓展”,是软件文件类型。使用DLL文件的好处是程序不需要在运行之初加载所有代码,只有在程序需要某个函数的时候才从DLL中取出。另外,使用DLL文件还可以减少程序的体积。

一个DLL文件的生成过程

  1. 新建项目-类库-名称为BuildeADll。
  2. 新建一个类,名称为Algorithms。
  3. 在类中定义一个方法,代码如下。
  4. 生成解决方案。
  5. 在路径:BuildeADll-bin-Debug下可以找到BuildeADll.dll文件。
namespace BuildeADll{    public class Algorithms    {        public static int[] BubbleSort(int[] source)        {            int i, j, temp;            for (i = 0; i < source.Length - 1; i++)            {                for (j = 0; j < source.Count() - 1 - i; j++)                {                    if (source[j] > source[j + 1])                    {                        temp = source[j];                        source[j] = source[j + 1];                        source[j + 1] = temp;                    }                }            }            return source;        }    }}

使用DLL文件

  1. 新建一个控制台应用程序,名称为UseDll。
  2. 引用刚才生成的Dll文件。引用-添加引用-浏览-找到dll文件位置并选择-确定。
  3. 添加命名空间。using BuildeADll;
  4. 在Main方法中调用。
namespace UseDll{    class Program    {        static void Main(string[] args)        {            int[] source = { 9, 3, 2, 5, 6, 7, 4, 1, 8, 0 };            int[] afterSort = Algorithms.BubbleSort(source);            for (int i = 0; i < afterSort.Length; i++)            {                Console.Write(afterSort[i] + " ");            }            Console.WriteLine();        }    }}

输出结果

这里写图片描述

总结

  Dll的好处在于封装了代码,提高了安全性,符合高内聚低耦合的规范。