this 關鍵字Solution/
├── AppleLib/ // Class Library 專案
│ └── Apple.cs
└── ConsoleApp/ // Console Application 專案
└── Program.cs (對應原 Example2.cs)
在 Visual Studio 中新增專案 → Class Library (.NET Framework / .NET Standard / .NET Core),命名為 AppleLib。
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 | 「資料與行為綁定,內部細節隱藏」— 物件導向核心原則 | 私有欄位 + 公開屬性/方法 |
csc /target:library /out:AppleLib.dll Apple.cs
/target:library:產生 DLL 而非 EXE/out::指定輸出檔名bin/Debug/netstandard2.0/AppleLib.dll (視目標架構而定)AppleLib → OKcsc /reference:AppleLib.dll Program.cs
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# 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 欄位 | 改用公開屬性或方法 |
| 執行時 FileNotFoundException | DLL 未複製至輸出目錄 | 專案參考會自動處理;命令列需手動複製 |
Company.Product.Module 避免型別名稱衝突。掌握類別設計與組件部署,是從「寫腳本」邁向「工程化開發」的關鍵一步。