首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> C# >> 關於C#

C# 實戰:建立與呼叫 DLL 動態連結庫完整指南(指令列編譯篇)

     編輯:關於C#

前言:為何使用 DLL?

DLL(Dynamic Link Library)實現程式碼模組化、重複使用與獨立部署。優勢包括:記憶體共用(多進程共享單一副本)、節省磁碟空間、易於版本升級(介面不變無需重新編譯呼叫端)、支援多語言互呼、便於國際化資源隔離。缺點為部署時需確保 DLL 存在。

實作步驟:建立 MyDLL.dll

1. 撰寫原始碼(兩個類別,同一命名空間)

Swap.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;
        }
    }
}

2. 指令列編譯為 DLL

開啟「Visual Studio 開發人員命令提示字元」,切換至原始碼目錄,執行:

csc /target:library /out:MyDLL.dll Swap.cs MaxCD.cs
  • /target:library:輸出 DLL 而非 EXE。
  • /out:MyDLL.dll:指定輸出檔名(省略則以第一個檔名為準)。

呼叫 DLL:建立 MyClient.exe

using 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);
    }
}

編譯呼叫端並參考 DLL

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

進階補充:Visual Studio 專案結構建議

  1. 類別庫專案:建立 MyLibrary 專案,編譯直接產出 MyLibrary.dll。
  2. 主控台專案:加入對 MyLibrary 的「專案參考」,Visual Studio 自動處理建置順序與複製 DLL。
  3. NuGet 封裝:將 DLL 打包為 NuGet 套件,發布至私有/公有源,實現跨專案、跨團隊版本化管理。

DLL 部署最佳實務

  • 採用並存組件(Side-by-Side)或 app.config probing 路徑管理版本。
  • 生產環境建議強簽名(Strong Name)並安裝至 GAC 或採用本地部署。
  • 注意 .NET Core / .NET 5+ 採用 .dll 為單一檔案部署單元,概念延續但工具鏈不同(dotnet build, dotnet pack)。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved