DLL(Dynamic Link Library)實現程式碼模組化、重複使用與獨立部署。優勢包括:記憶體共用(多進程共享單一副本)、節省磁碟空間、易於版本升級(介面不變無需重新編譯呼叫端)、支援多語言互呼、便於國際化資源隔離。缺點為部署時需確保 DLL 存在。
MyDLL.dllSwap.cs - 交換兩數值:
using System;
namespace MyMethods {
public class SwapClass {
public static bool Swap(ref long i, ref long j) {
i = i + j;
j = i - j;
i = i - j;
return true;
}
}
}
MaxCD.cs - 計算最大公約數:
using System;
namespace MyMethods {
public class MaxCDClass {
public static long MaxCD(long i, long j) {
long a = i > j ? i : j;
long b = i > j ? j : i;
long temp = a % b;
while (temp != 0) {
a = b;
b = temp;
temp = a % b;
}
return b;
}
}
}
開啟「Visual Studio 開發人員命令提示字元」,切換至原始碼目錄,執行:
csc /target:library /out:MyDLL.dll Swap.cs MaxCD.cs
/target:library:輸出 DLL 而非 EXE。/out:MyDLL.dll:指定輸出檔名(省略則以第一個檔名為準)。MyClient.exeusing System;
using MyMethods; // 引用命名空間
class MyClient {
public static void Main(string[] args) {
if (args.Length != 2) {
Console.WriteLine("Usage: MyClient ");
return;
}
long num1 = long.Parse(args[0]);
long num2 = long.Parse(args[1]);
SwapClass.Swap(ref num1, ref num2);
Console.WriteLine("Swap result: num1 = {0}, num2 = {1}", num1, num2);
long maxcd = MaxCDClass.MaxCD(num1, num2);
Console.WriteLine("MaxCD of {0} and {1} is {2}", num1, num2, maxcd);
}
}
csc /out:MyClient.exe /reference:MyDLL.dll MyClient.cs
/reference:MyDLL.dll:告知編譯器解析 MyMethods 命名空間中的型別。> MyClient 123 456
Swap result: num1 = 456, num2 = 123
MaxCD of 456 and 123 is 3
MyLibrary 專案,編譯直接產出 MyLibrary.dll。MyLibrary 的「專案參考」,Visual Studio 自動處理建置順序與複製 DLL。app.config probing 路徑管理版本。.NET Core / .NET 5+ 採用 .dll 為單一檔案部署單元,概念延續但工具鏈不同(dotnet build, dotnet pack)。