GST C# 命名規範標準
本文件定義 GatherSystemTech 團隊的 C# 命名規範,基於 Microsoft .NET 命名指南並加入團隊慣例。
1. 專案命名 (.csproj)
1.1 底層框架專案
格式:GST.{Layer}.{Module}
| 層級 | 格式 | 範例 |
|---|---|---|
| 核心抽象 | GST.Core.{Domain} | GST.Core.Abstractions, GST.Core.Common |
| 功能插件 | GST.Plugin.{FeatureName} | GST.Plugin.UserManagement, GST.Plugin.AuditTrail |
| 協定插件 | GST.Plugin.{Protocol} | GST.Plugin.Modbus, GST.Plugin.S7 |
| UI 抽象 | GST.UI.{Framework} | GST.UI.Wpf, GST.UI.WinForms |
| 服務基礎設施 | GST.ServiceInfrastructure.{Component} | GST.ServiceInfrastructure.Host |
| 工具 | GST.Tools.{ToolName} | GST.Tools.LocalizationGenerator |
1.2 應用層專案
通用應用格式:GST.App.{ProjectName}
GST.App.ProcessVision # UI 層
GST.App.ProcessVision.Core # 業務邏輯層
公司專屬應用格式:{Company}.{ProjectName}
當應用程式需要以客戶/合作公司品牌發布時,允許使用公司前綴:
Jope.SMB.Core # 喬璞 SMB 業務邏輯
Jope.SMB.WPF # 喬璞 SMB UI 層
Leyu.{ProjectName} # 樂宇專案
說明:此規則適用於上包案件,軟體對外顯示需使用客戶公司名稱的情境。
1.3 測試專案
格式:{OriginalProject}.Tests
GST.Core.Common.Tests
GST.Plugin.UserManagement.Tests
Jope.SMB.Core.Tests
2. 命名空間
2.1 格式
標準格式:{ProjectName}.{Subdomain}
// 底層框架
namespace GST.Core.Abstractions.Audit;
namespace GST.Plugin.UserManagement.Services;
namespace GST.Plugin.Modbus.Rtu;
// 應用層
namespace GST.App.ProcessVision.ViewModels;
namespace Jope.SMB.Core.Devices;
namespace Jope.SMB.WPF.Services;
2.2 規則
- 最多 4 層深度
- 與資料夾結構對應
- 使用 File-scoped namespace(C# 10+)
// ✅ 正確 - File-scoped namespace
namespace GST.Core.Abstractions.Audit;
public interface IAuditService { }
// ❌ 避免 - Block-scoped namespace
namespace GST.Core.Abstractions.Audit
{
public interface IAuditService { }
}
3. 檔案命名
所有檔案使用 PascalCase,與主要類別/介面同名。
| 類型 | 格式 | 範例 |
|---|---|---|
| 介面 | I{ConceptName}.cs | IUserService.cs, ICacheService.cs |
| 服務 | {Concept}Service.cs | UserService.cs, MemoryCacheService.cs |
| Repository | {Entity}Repository.cs | UserRepository.cs |
| 實體 | {Concept}Entity.cs | UserEntity.cs, RoleEntity.cs |
| Request DTO | {Action}{Concept}Request.cs | CreateUserRequest.cs |
| Response DTO | {Concept}Response.cs | LoginResponse.cs |
| 異常 | {Concept}Exception.cs | ModbusException.cs |
| 擴展方法 | {TargetType}Extensions.cs | StringExtensions.cs |
| 輔助工具 | {Concept}Helper.cs | RetryHelper.cs |
| 選項/配置 | {Concept}Options.cs | AuthenticationOptions.cs |
| 工廠 | {Concept}Factory.cs | ControllerFactory.cs |
| 列舉 | {Concept}.cs(單數) | AlarmSeverity.cs |
| ViewModel | {Name}ViewModel.cs | MainViewModel.cs |
| Converter | {Name}Converter.cs | BoolToVisibilityConverter.cs |
3.1 Helper vs Extensions 區分
| 類型 | 用途 | 範例 |
|---|---|---|
| Extensions | 擴展方法(有 this 參數) | StringExtensions.cs |
| Helper | 靜態工具方法(無 this 參數) | RetryHelper.cs |
// Extensions - 擴展方法
public static class StringExtensions
{
public static bool IsNullOrEmpty(this string value) => string.IsNullOrEmpty(value);
}
// Helper - 靜態工具方法
public static class RetryHelper
{
public static async Task<T> ExecuteWithRetryAsync<T>(Func<Task<T>> action, int maxRetries) { }
}
4. 類別/介面命名
4.1 命名模式
| 類型 | 格式 | 範例 |
|---|---|---|
| 介面 | I{ConceptName} | IUserService, ICacheService |
| 抽象類別 | {Concept}Base | ViewModelBase, PresenterBase |
| 服務 | {Concept}Service | UserService, RoleService |
| Repository | {Entity}Repository | UserRepository |
| 工廠 | {Concept}Factory | ControllerFactory |
| 控制器(設備) | {DeviceName}Controller | TaieFcController |
| 管理器 | {Concept}Manager | AlarmManager |
| 建造者 | {Concept}Builder | CommandBuilder |
| 處理器 | {Concept}Handler | MessageHandler |
4.2 Service vs Manager vs Handler 區分
| 類型 | 職責 | 範例 |
|---|---|---|
| Service | 業務邏輯(CRUD、驗證、計算) | UserService, AuthenticationService |
| Manager | 資源管理(生命週期、狀態、池化) | ConnectionManager, AlarmManager |
| Handler | 事件/訊息處理(回應特定事件) | MessageHandler, ErrorHandler |
4.3 存取修飾符
| 修飾符 | 用途 |
|---|---|
public interface | 對外合約 |
public abstract class | 可繼承基類 |
public sealed class | 不可繼承的公開類別 |
internal class | 內部實現(最常用) |
internal sealed class | 內部不可繼承 |
5. 方法命名
5.1 命名模式
| 操作 | 格式 | 範例 |
|---|---|---|
| 取得單一 | Get{Entity}[By{Key}]Async | GetUserByIdAsync |
| 取得多個 | Get{Entities}Async | GetUsersAsync, GetAllRolesAsync |
| 建立 | Create{Entity}Async | CreateUserAsync |
| 更新 | Update{Entity}Async | UpdateUserAsync |
| 刪除 | Delete{Entity}Async | DeleteUserAsync |
| 驗證 | Validate{Concept}Async | ValidatePasswordAsync |
| 確認 | Verify{Concept}Async | VerifyChainAsync |
| 檢查存在 | {Entity}ExistsAsync | UserExistsAsync |
| 嘗試操作 | Try{Action} | TryParse, TryGetValue |
| 事件處理 | On{EventName} | OnConnected, OnError |
5.2 非同步方法規則
- 所有非同步方法必須以
Async結尾 - 必須包含
CancellationToken參數
// ✅ 正確
public async Task<User> GetUserByIdAsync(
Guid id,
CancellationToken cancellationToken = default);
// ❌ 錯誤 - 缺少 Async 後綴和 CancellationToken
public async Task<User> GetUserById(Guid id);
6. 變數命名
6.1 命名規則
| 類型 | 格式 | 範例 |
|---|---|---|
| 私有欄位 | _camelCase | _userRepository, _logger |
| 公開屬性 | PascalCase | Username, IsActive |
| 參數 | camelCase | userId, cancellationToken |
| 區域變數 | camelCase | user, result |
| 常數 | PascalCase | MaxRetryCount, DefaultTimeout |
| 靜態唯讀 | PascalCase | Empty, Default |
6.2 布林命名
使用 Is/Has/Can/Should 前綴:
// ✅ 正確
public bool IsActive { get; set; }
public bool HasPermission { get; set; }
public bool CanExecute { get; set; }
public bool ShouldRetry { get; set; }
// ❌ 避免
public bool Active { get; set; } // 不清楚是動詞還是形容詞
public bool Permission { get; set; } // 不清楚是什麼類型
7. 列舉命名
7.1 一般列舉
使用單數名稱,PascalCase 值:
public enum AlarmSeverity
{
Critical = 0,
High = 1,
Medium = 2,
Low = 3
}
public enum ChannelState
{
Disconnected = 0,
Connecting = 1,
Connected = 2,
Error = 3
}
7.2 Flags 列舉
使用複數名稱:
[Flags]
public enum FilePermissions
{
None = 0,
Read = 1,
Write = 2,
Execute = 4,
All = Read | Write | Execute
}
8. 資料夾結構
8.1 底層專案結構
GST.Plugin.{FeatureName}/
├── Abstractions/ # 介面定義
├── Models/ # 資料模型(Entity, DTO)
├── Services/ # 服務實現
├── Repositories/ # 資料存取
├── Extensions/ # 擴展方法
├── Helpers/ # 輔助工具
├── Exceptions/ # 自訂異常
└── Configuration/ # 配置相關
8.2 應用層專案結構
{App}.WPF/ # UI 層
├── Controls/ # 自訂控制項
├── Converters/ # 值轉換器
├── Resources/ # 資源檔
│ ├── Icons/
│ └── Localization/
├── Services/ # UI 服務
├── ViewModels/ # ViewModel
├── Views/ # 視圖(XAML)
└── Themes/ # 主題
{App}.Core/ # 業務邏輯層
├── Models/ # 領域模型
├── Services/ # 業務服務
├── Repositories/ # 資料存取
└── {Domain}/ # 依領域分組
├── Models/
└── Services/
9. XML 文件註解
9.1 規則
- 所有
public成員必須有 XML 註解 - 使用英文撰寫(避免編碼問題)
- 簡潔明瞭,避免重複方法名稱
9.2 範例
/// <summary>
/// Provides user management operations including CRUD and authentication.
/// </summary>
public interface IUserService
{
/// <summary>
/// Gets a user by their unique identifier.
/// </summary>
/// <param name="id">The unique identifier of the user.</param>
/// <param name="cancellationToken">A token to cancel the operation.</param>
/// <returns>The user if found; otherwise, null.</returns>
/// <exception cref="ArgumentException">Thrown when id is empty.</exception>
Task<User?> GetByIdAsync(Guid id, CancellationToken cancellationToken = default);
}
10. 記錄型別 (Record)
用於不可變的資料傳輸物件(DTO):
// Request DTO
public record CreateUserRequest
{
public required string Username { get; init; }
public required string Password { get; init; }
public string DisplayName { get; init; } = string.Empty;
}
// Response DTO
public record LoginResponse
{
public required string Token { get; init; }
public required DateTime ExpiresAt { get; init; }
}
// Result 型別
public record AuditChainVerificationResult
{
public required bool IsValid { get; init; }
public required int TotalEntriesVerified { get; init; }
public IReadOnlyList<string> Errors { get; init; } = [];
}
11. 禁止事項
11.1 命名禁止
// ❌ 禁止 - 匈牙利命名法
string strName;
int iCount;
bool bIsActive;
// ❌ 禁止 - 縮寫(除非是通用縮寫如 Id, Url, Html)
string usrNm;
int cnt;
// ❌ 禁止 - 底線開頭的公開成員
public string _username;
// ❌ 禁止 - 全大寫(除了縮寫詞)
public const int MAXRETRYCOUNT = 3;
11.2 通用縮寫(允許使用)
| 縮寫 | 全名 |
|---|---|
| Id | Identifier |
| Url | Uniform Resource Locator |
| Html | HyperText Markup Language |
| Xml | Extensible Markup Language |
| Json | JavaScript Object Notation |
| Dto | Data Transfer Object |
| Io | Input/Output |
| Ui | User Interface |
| Api | Application Programming Interface |
12. 專案前綴對照表
| 前綴 | 用途 | 範例 |
|---|---|---|
GST.* | 底層框架 | GST.Core.Common, GST.Plugin.Modbus |
GST.App.* | 通用應用 | GST.App.ProcessVision |
Jope.* | 喬璞專屬應用 | Jope.SMB.Core |
Leyu.* | 樂宇專屬應用 | Leyu.{ProjectName} |
{Company}.* | 其他公司專屬 | 依客戶需求 |
13. 檢查清單
新建專案或程式碼審查時,確認以下項目:
專案層級
- 專案名稱符合
GST.*或{Company}.*格式 - 測試專案使用
.Tests後綴 - 使用 File-scoped namespace
檔案層級
- 檔案名稱與主要類別同名
- 介面檔案使用
I前綴 - 適當使用 Entity/Request/Response 後綴
類別層級
- 介面使用
I前綴 - 抽象類別使用
Base後綴 - Service/Manager/Handler 區分正確
成員層級
- 私有欄位使用
_camelCase - 公開屬性使用
PascalCase - 非同步方法使用
Async後綴 - 布林屬性使用
Is/Has/Can/Should前綴
文件
- 所有 public 成員有 XML 註解
- 註解使用英文
版本歷史
| 版本 | 日期 | 變更說明 |
|---|---|---|
| 1.0 | 2025-01-17 | 初版建立 |