跳至主要内容

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}.csIUserService.cs, ICacheService.cs
服務{Concept}Service.csUserService.cs, MemoryCacheService.cs
Repository{Entity}Repository.csUserRepository.cs
實體{Concept}Entity.csUserEntity.cs, RoleEntity.cs
Request DTO{Action}{Concept}Request.csCreateUserRequest.cs
Response DTO{Concept}Response.csLoginResponse.cs
異常{Concept}Exception.csModbusException.cs
擴展方法{TargetType}Extensions.csStringExtensions.cs
輔助工具{Concept}Helper.csRetryHelper.cs
選項/配置{Concept}Options.csAuthenticationOptions.cs
工廠{Concept}Factory.csControllerFactory.cs
列舉{Concept}.cs(單數)AlarmSeverity.cs
ViewModel{Name}ViewModel.csMainViewModel.cs
Converter{Name}Converter.csBoolToVisibilityConverter.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}BaseViewModelBase, PresenterBase
服務{Concept}ServiceUserService, RoleService
Repository{Entity}RepositoryUserRepository
工廠{Concept}FactoryControllerFactory
控制器(設備){DeviceName}ControllerTaieFcController
管理器{Concept}ManagerAlarmManager
建造者{Concept}BuilderCommandBuilder
處理器{Concept}HandlerMessageHandler

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}]AsyncGetUserByIdAsync
取得多個Get{Entities}AsyncGetUsersAsync, GetAllRolesAsync
建立Create{Entity}AsyncCreateUserAsync
更新Update{Entity}AsyncUpdateUserAsync
刪除Delete{Entity}AsyncDeleteUserAsync
驗證Validate{Concept}AsyncValidatePasswordAsync
確認Verify{Concept}AsyncVerifyChainAsync
檢查存在{Entity}ExistsAsyncUserExistsAsync
嘗試操作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
公開屬性PascalCaseUsername, IsActive
參數camelCaseuserId, cancellationToken
區域變數camelCaseuser, result
常數PascalCaseMaxRetryCount, DefaultTimeout
靜態唯讀PascalCaseEmpty, 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 通用縮寫(允許使用)

縮寫全名
IdIdentifier
UrlUniform Resource Locator
HtmlHyperText Markup Language
XmlExtensible Markup Language
JsonJavaScript Object Notation
DtoData Transfer Object
IoInput/Output
UiUser Interface
ApiApplication 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.02025-01-17初版建立