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

使用 C# 輕鬆建立 .NET 元件:從類別設計到 DLL 發布的完整實戰指南

     編輯:關於C語言

.NET 元件開發範式轉變

傳統 COM 元件開發門檻高,.NET 與 C# 讓元件開發變得平易近人。C# 被稱為「面向元件的語言」,原生支援屬性、事件、介面、版本控制等元件級特性。

建立命名空間與類別

namespace ComponentCS {
    public class StringComponent {
        private string[] stringsSet;
        
        // 唯讀屬性
        public int StringLength => stringsSet.Length;
        
        // 方法
        public void Modify(int index, string value) {
            if (index < 0 || index >= stringsSet.Length)
                throw new IndexOutOfRangeException();
            stringsSet[index] = value;
            OnModify();
        }
        
        // 建構函式
        public StringComponent() {
            stringsSet = new[] { "C# String 0", "C# String 1", "C# String 2", "C# String 3" };
        }
        
        public string GetString(int index) {
            if (index < 0 || index >= stringsSet.Length)
                throw new IndexOutOfRangeException();
            return stringsSet[index];
        }
    }
}

命名空間進階用法

  • 巢狀命名空間:namespace Outer { namespace Inner { class C {} } } → Outer.Inner.C
  • 跨檔案分散定義:同一命名空間可分佈在多個 .cs 檔
  • 單一檔案多命名空間:namespace A {} namespace B {}

欄位 vs 屬性:封裝性的體現

特性欄位屬性
語法public int Age;public int Age { get; set; }
封裝直接存取透過存取子控制邏輯
唯讀readonly僅 get
傳遞可 ref/out不可 ref/out
介面不可定義可定義

原則:公開成員優先用屬性,保留未來加入驗證、通知、延遲載入的彈性。

建構函式:實例初始化契約

  • 與類別同名、無回傳型別
  • 可多載、可鏈結 this(...)
  • 執行時機:new 運算子配置記憶體後、傳回參考前
  • 垃圾收集器自動管理生命週期

例外處理:健壯元件的基石

使用框架例外

throw new IndexOutOfRangeException();

自訂例外型別(建議繼承 ApplicationException)

public class MyApplicationException : ApplicationException {
    public string DetailMessage { get; }
    public MyApplicationException(string msg) => DetailMessage = msg;
}

// 使用
public string GetString(int index) {
    try {
        if (index < 0 || index >= stringsSet.Length)
            throw new MyApplicationException("索引超出範圍");
    } catch (MyApplicationException ex) {
        Console.WriteLine(ex.DetailMessage);
    } catch (Exception ex) {
        Console.WriteLine(ex.Message);
    }
    return stringsSet[index];
}

事件機制:鬆耦合通知

宣告事件

public event EventHandler Modified;

引發事件的保護模式

private void OnModify() {
    Modified?.Invoke(this, EventArgs.Empty); // C# 6.0 null 條件運算子
    // 舊寫法:
    // var handler = Modified;
    // if (handler != null) handler(this, EventArgs.Empty);
}

訂閱與取消訂閱

var component = new StringComponent();
component.Modified += Component_Modified;  // 訂閱
component.Modified -= Component_Modified;  // 取消訂閱

private void Component_Modified(object sender, EventArgs e) {
    Console.WriteLine("資料已變更");
}

完整元件類別範例

using System;

namespace ComponentCS {
    public class StringComponent {
        private string[] stringsSet;
        public event EventHandler Modified;
        
        public int StringLength => stringsSet.Length;
        
        public void Modify(int index, string value) {
            if (index < 0 || index >= stringsSet.Length)
                throw new IndexOutOfRangeException();
            stringsSet[index] = value;
            OnModify();
        }
        
        private void OnModify() => Modified?.Invoke(this, EventArgs.Empty);
        
        public StringComponent() {
            stringsSet = new[] { "C# String 0", "C# String 1", "C# String 2", "C# String 3" };
        }
        
        public string GetString(int index) {
            if (index < 0 || index >= stringsSet.Length)
                throw new IndexOutOfRangeException();
            return stringsSet[index];
        }
    }
}

編譯為 DLL:元件發布標準形式

csc.exe /target:library /debug+ /out:StringComponent.dll StringComponent.cs
  • /target:library:產生 DLL 而非 EXE
  • /debug+:產生 .pdb 方便偵錯
  • /out:指定輸出檔名

優點:原始碼保護、IL 已編譯載入快、版本管理、跨語言互通(VB.NET、F# 皆可引用)。

進階元件開發考量

  • 強名稱簽署:sn -k key.snk + /keyfile:key.snk → GAC 部署、版本綁定
  • 版本資訊:[assembly: AssemblyVersion("1.0.0.0")]
  • API 設計原則:最小介面、不可變性、明確失敗、文件化
  • 相依性管理:NuGet 套件、PackageReference
  • 測試:單元測試覆蓋公用 API、邊界條件、例外路徑

十分鐘建立基礎元件,一生精進元件架構。C# 賦予開發者強大的元件建構能力,關鍵在於設計意圖與工程紀律的結合。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved