一般情況下,如果在新建或添加時選擇“windows應用程序”或“控制台應用程序”時,結果都會被編譯成exe,而選擇“類庫”時就會被編譯成dll。也可以在項目屬性中更改其輸出類型,如下圖:
下面上一個創建dll並引用的實例.
1.新建一個項目,選擇類庫,命名DllTest。然后寫一個類,里面包含一些方法什么的,為了突出主題,作為例子,我就寫了一個簡單的類,如下:
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace DllTest { // 求兩個數或三個數的最大值 public static class TestClass { public static int GetMax(int a, int b) { return (a > b ? a : b); } public static int GetMax(int a, int b, int c) { return ((a > b ? a : b) > c ? (a > b ? a : b) : c); } } }
點“生成”后在 bin\debug 文件夾下會出現一個與項目名同名的dll文件
2.再新建一個項目(也可以建一個新的解決方案)命名DllRef這時就不要選類庫類型了,Win應用和Console任選一個,然后添加對剛剛生成的dll文件的引用,並using其命名空間。
這時在本項目的bin\Debug文件夾下也出現了一個dll文件,就是我們引用的那個。
寫相關調用語句:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using DllTest; namespace DllRef { class Program { static void Main(string[] args) { Console.WriteLine(TestClass.GetMax(5, 6)); Console.WriteLine(TestClass.GetMax(7, 8, 9)); } } }
將第二個項目設為啟動項,試運行成功。就是說我們在新的項目中,用到了封裝在dll中的類。
dll為一個程序集,可以被不同的程序重復調用,只要將其成功引用並using其命名空間即可。