| 類型 | 命名 | 範例 | 備註 |
|---|---|---|---|
| const | PascalCase | public const int MaxRetry = 3; | 編譯期常值 |
| static readonly | PascalCase | public static readonly TimeSpan DefaultTimeout = TimeSpan.FromSeconds(30); | 執行期常值,支援參考型別 |
舊版習慣全大寫底線 (MAX_RETRY) 亦可接受,但 **PascalCase 符合 .NET 標準框架風格** (如 Int32.MaxValue)。
private int _maxHeight; private readonly string _connectionString;this.maxHeight 混淆。
private int _minHeight = int.MinValue;
public int MinHeight
{
get => _minHeight;
set
{
// 即使目前無邏輯,仍保留 setter 結構
_minHeight = value;
}
}
// 類別內部也必須透過屬性存取
public void SetHeight(int h) => MinHeight = h; // ✅
// _minHeight = h; // ❌ 繞過屬性,未來加驗證/通知會失效
// ❌ 錯誤:欄位初始化器順序問題
private int _a = _b + 1; // _b 尚未初始化 (為 0)
private int _b = 10;
// ✅ 正確:建構函式初始化
private int _a, _b;
public MyClass() { _b = 10; _a = _b + 1; }
// 或使用 Lazy 延遲初始化
private readonly Lazy _resource =
new Lazy(() => new ExpensiveResource());
// 自動實作屬性 (編譯器產生隱藏 backing field)
public int MinHeight { get; set; } = 0;
// 唯讀自動屬性 (C# 9 init)
public int MaxHeight { get; init; } = 100;
// 唯讀 + 建構函式指定
public class Config
{
public string ConnectionString { get; }
public Config(string connStr) => ConnectionString = connStr;
}
// Record (C# 9) - 不可變資料型別
public record Config(string ConnectionString, int Timeout = 30);
| 識別項 | 慣例 | 範例 |
|---|---|---|
| 命名空間 | PascalCase | MyCompany.Project.Module |
| 類別/結構/介面/列舉/委派 | PascalCase | Customer, IRepository, Color, EventHandler |
| 公用/受保護欄位 (極少用) | PascalCase | — |
| 私有/內部欄位 | _camelCase | _firstName, _items |
| 屬性/方法/事件 | PascalCase | FirstName, CalculateTotal, OnSaved |
| 區域變數/參數 | camelCase | firstName, items, cancellationToken |
| 常數 | PascalCase | MaxRetries, DefaultPageSize |
| 泛型型別參數 | T + PascalCase | TEntity, TKey, TResult |
**統一命名風格 + 嚴格屬性封裝** 是可維護 C# 代碼庫的基石。配合 .editorconfig 強制風格、StyleCop.Analyzers/Roslynator 靜態分析,即可在團隊層面落實規範。