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

C# 入門教學 (二):自訂類別、建構函式、封裝與動態連結庫建置

     編輯:關於C語言

學習目標

  • 定義自訂類別與成員存取修飾詞
  • 理解建構函式與 this 關鍵字
  • 實作封裝:私有欄位 + 公開存取方法
  • 將類別編譯為 DLL 並被其他專案參考

範例專案結構

Solution/
├── AppleLib/          // Class Library 專案
│   └── Apple.cs
└── ConsoleApp/        // Console Application 專案
    └── Program.cs     (對應原 Example2.cs)

步驟 1:建立類別庫專案

在 Visual Studio 中新增專案 → Class Library (.NET Framework / .NET Standard / .NET Core),命名為 AppleLib。

步驟 2:撰寫 Apple 類別

namespace AppleLib
{
    /// 
    /// 蘋果品種資料模型
    /// 
    public class Apple
    {
        // 私有欄位:封裝內部資料
        private string _variety;

        /// 
        /// 建構函式:初始化品種
        /// 
        /// 蘋果品種名稱
        public Apple(string variety)
        {
            _variety = variety ?? string.Empty; // 防禦性程式設計
        }

        /// 
        /// 唯讀屬性:對外暴露品種 (現代寫法取代 GetVariety())
        /// 
        public string Variety => _variety;

        /// 
        /// 顯示品種至主控台
        /// 
        public void OutputVariety()
        {
            Console.WriteLine(_variety);
        }
    }
}

關鍵概念解析

概念說明程式碼對應
public class公開類別,允許其他組件建立實例public class Apple
private field隱藏實作細節,防止外部任意修改private string _variety
Constructor同名方法,new 時自動呼叫,保證物件有效初始化public Apple(string variety)
this參考目前實例,區分參數與欄位同名時使用_variety = variety (慣用前綴 _ 避免衝突)
Encapsulation「資料與行為綁定,內部細節隱藏」— 物件導向核心原則私有欄位 + 公開屬性/方法

步驟 3:編譯類別庫

命令列方式 (教學用)

csc /target:library /out:AppleLib.dll Apple.cs
  • /target:library:產生 DLL 而非 EXE
  • /out::指定輸出檔名

Visual Studio 方式 (實務標準)

  1. 右鍵專案 → Build (或 Ctrl+Shift+B)
  2. 輸出位於 bin/Debug/netstandard2.0/AppleLib.dll (視目標架構而定)

步驟 4:建立主控台應用程式並參考 DLL

專案參考 (推薦)

  1. 方案總管 → ConsoleApp 專案 → Dependencies 右鍵 → Add Project Reference
  2. 勾選 AppleLib → OK

命令列參考 (教學用)

csc /reference:AppleLib.dll Program.cs

步驟 5:撰寫主程式使用 Apple 類別

using System;
using AppleLib; // 匯入命名空間

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            // 建立三個實例
            Apple mac = new Apple("Macintosh");
            Apple granny = new Apple("Granny Smith");
            Apple cortland = new Apple("Cortland");

            // 呼叫方法
            mac.OutputVariety();
            granny.OutputVariety();
            cortland.OutputVariety();

            // 使用屬性 (現代慣用寫法)
            Console.WriteLine($"第一個蘋果品種:{mac.Variety}");

            Console.ReadKey(); // 暫停畫面
        }
    }
}

執行結果

Macintosh
Granny Smith
Cortland
第一個蘋果品種:Macintosh

進階補充:現代 C# 語法糖

// 唯讀屬性簡寫 (C# 6+)
public string Variety => _variety;

// 自動實作屬性 (若無額外邏輯)
public string Variety { get; }

// 建構函式參數直接指派給屬性 (C# 12+ primary constructors)
public class Apple(string Variety)
{
    public string Variety { get; } = Variety;
    public void OutputVariety() => Console.WriteLine(Variety);
}

常見錯誤與除錯

錯誤現象原因解決
CS0246: 找不到型別 'Apple'未加 using AppleLib; 或未參考 DLL檢查專案參考與 using 指示詞
CS0122: 'Apple._variety' 無法存取嘗試在外部直接存取 private 欄位改用公開屬性或方法
執行時 FileNotFoundExceptionDLL 未複製至輸出目錄專案參考會自動處理;命令列需手動複製

總結

  1. 類別即類型藍圖:定義資料 (欄位/屬性) 與行為 (方法/建構函式)。
  2. 封裝保護不變條件:私有欄位 + 公開介面 = 可控的狀態變更。
  3. DLL 實現程式碼重用:編譯為組件,跨專案參考,支援版本管理與 NuGet 發布。
  4. 命名空間組織架構:Company.Product.Module 避免型別名稱衝突。

掌握類別設計與組件部署,是從「寫腳本」邁向「工程化開發」的關鍵一步。

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