┌─────────────────────────────────────┐ │ 程式 (Program) │ 一或多個原始檔 (.cs) ├─────────────────────────────────────┤ │ 命名空間 (Namespace) │ 邏輯分組,防止名稱衝突 ├─────────────────────────────────────┤ │ 類型 (Type) │ Class, Struct, Interface, Enum, Delegate ├─────────────────────────────────────┤ │ 成員 (Member) │ Field, Method, Property, Event, Constructor ├─────────────────────────────────────┤ │ 組件 (Assembly) │ .exe / .dll 物理部署單位,含 IL + 中繼資料 └─────────────────────────────────────┘
using System; // 引用 System 命名空間
namespace Acme.Collections // 邏輯分組:Acme.Collections
{
public class Stack // 公開類別:Stack
{
Entry top; // 私有欄位:頂端節點 (內部類別 Entry)
public void Push(object data) // 公開方法:推入
{
top = new Entry(top, data); // 建立新節點指向舊頂端
}
public object Pop() // 公開方法:彈出
{
if (top == null)
throw new InvalidOperationException(); // 空堆疊例外
object result = top.data; // 取出資料
top = top.next; // 移動頂端指標
return result; // 回傳資料
}
// 巢狀類別:節點定義
class Entry
{
public Entry next; // 下一個節點
public object data; // 儲存資料
public Entry(Entry next, object data) // 建構函式
{
this.next = next;
this.data = data;
}
}
}
}
csc /t:library acme.cs
// 產生 acme.dll (組件)
// /t:library 表示無進入點,產生 .dll
// 組件包含:IL 程式碼 + 中繼資料 (型別定義、成員簽章、版本、公開金鑰等)
using System;
using Acme.Collections; // 匯入命名空間,簡化型別名稱
class Test
{
static void Main() // 進入點
{
Stack s = new Stack(); // 完整名稱:Acme.Collections.Stack
s.Push(1);
s.Push(10);
s.Push(100);
Console.WriteLine(s.Pop()); // 100 (LIFO)
Console.WriteLine(s.Pop()); // 10
Console.WriteLine(s.Pop()); // 1
}
}
csc /r:acme.dll test.cs
// /r:acme.dll 參考外部組件
// 產生 test.exe
// 執行 test.exe → 輸出 100, 10, 1
Major.Minor.Build.Revision,強命名組件含公開金鑰簽章System.Collections.Genericusing 指令簡化名稱,不影響編譯輸出using MyList = System.Collections.Generic.List<int>;| 分類 | 關鍵字 | 記憶體 | 繼承 | 適用場景 |
|---|---|---|---|---|
| 參考型別 | class | 堆疊參考 → 堆積物件 | 單一繼承 + 介面 | 複雜物件、需多態、共享參考 |
| 實值型別 | struct | 堆疊內嵌 | 不可繼承 (隱含 sealed),可實作介面 | 小型資料結構、高效能、不可變 |
| 介面 | interface | 契約定義 | 多重實作 | 解耦、多型契約 |
| 列舉 | enum | 整數基礎型別 | 不可繼承 | 具名常數集合 |
| 委派 | delegate | 方法參考 | 密封類別 | 事件、回呼、函式指標 |
const (編譯期)、readonly (執行期初始化)、static (型別層級)get/set/init 存取子、自動實作屬性、索引器 this[int i]event 關鍵字、標準 EventHandler<TEventArgs> 模式~ClassName() (非確定性清理)operator +、implicit/explicit 轉換// File1.cs
namespace Demo { public class A { public B Ref; } }
// File2.cs
namespace Demo { public class B { public A Ref; } }
// 編譯:csc File1.cs File2.cs
// C# 編譯器一次處理所有原始檔,相互參考無需前向宣告
// 概念上等同合併成單一大檔案後編譯
Src/MyApp/Domain/Entities/User.cs → namespace MyApp.Domain.Entitiesinternal,成員預設 privatepublic 型別/成員一旦發布即難變更,優先用 internal理解「原始碼 → 命名空間/類型/成員 → 組件 → CLR 執行」的完整鏈路,是掌握 C# 工程化開發的基石。無論是設計領域模型、劃分微服務邊界、排查組件載入失敗、或優化啟動效能,這五大核心概念始終貫穿始終。