萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP.NET 程式設計

.NET 命名規範完整指南:PascalCase、camelCase、底線前綴、介面慣例與程式碼組織原則

核心命名規則速查表

識別項類型慣例範例適用範圍
類別、結構、介面、列舉、委派、命名空間、公用方法、公用屬性、事件**PascalCase** (每個單字首字大寫)`DataGrid`, `GetUserList`, `UserName`, `OnClick`Public/Protected/Internal 成員
區域變數、方法參數、私有欄位 (非唯讀)**camelCase** (首單字小寫,後續單字大寫)`userName`, `productId`, `_connectionString`Private/區域範圍
私有/受保護 實例欄位**_camelCase** (底線前綴 + camelCase)`_productId`, `_connectionString`區分欄位與區域變數,避免 `this.`
常數 (const)、靜態唯讀欄位**PascalCase**`MaxRetryCount`, `DefaultConnectionString`視為公用契約一部分
介面名稱**IPascalCase** (前綴 I + PascalCase)`IConvertible`, `IRepository`慣例強制,便於識別
泛型型別參數**TPascalCase** (前綴 T + PascalCase)`TEntity`, `TKey`, `TResult`單字母 T 亦可接受
自訂屬性類別**PascalCase + Attribute** 後綴`TableAttribute`, `RequiredAttribute`使用時可省略 Attribute
自訂例外類別**PascalCase + Exception** 後綴`ValidationException`, `ConcurrencyException`繼承 Exception
非同步方法**PascalCase + Async** 後綴`GetUserAsync`, `SaveChangesAsync`Task-based Asynchronous Pattern (TAP)
布林屬性/方法**Is/Can/Has/Should + PascalCase**`IsValid`, `CanDelete`, `HasChildren`語意清晰

詳細規範與程式碼範例

1. 類別與公用成員:PascalCase

public class DataGrid
{
    public void DataBind() { }
    public int RowCount { get; set; }
    public event EventHandler RowDataBound;
}

2. 區域變數與參數:camelCase

public class Product
{
    private string _productId;      // 私有欄位:_camelCase
    private string _productName;

    public void AddProduct(string productId, string productName) // 參數:camelCase
    {
        var tempList = new List(); // 區域變數:camelCase
        // ...
    }
}

3. 匈牙利命名法 (Legacy/特定團隊規範)

部分團隊仍沿用前綴標示型別:

  • `int iCount`, `string strName`, `bool bFlag`
  • 控制項:`lblTitle` (Label), `btnSubmit` (Button), `txtUserName` (TextBox), `gvUserList` (GridView), `ddlCategory` (DropDownList)

建議:現代 .NET 開發**不推薦**型別前綴,IDE 已提供型別資訊;控制項前綴若團隊共識可保留,否則一律 PascalCase/camelCase。

4. 介面:I 前綴

public interface IConvertible
{
    byte ToByte();
    DateTime ToDateTime();
}

5. 自訂屬性與例外

[AttributeUsage(AttributeTargets.Class)]
public class TableAttribute : Attribute { }

public class DataAccessException : Exception
{
    public DataAccessException(string message, Exception inner) : base(message, inner) { }
}

6. 方法命名:動賓片語

public class FileService
{
    public void CreateFile(string filePath) { }
    public string GetFilePath(string fileName) { }
    public bool DeleteFile(string filePath) { }
}

7. 迴圈變數與有意義命名

// 簡單迴圈可用 i, j, k
for (int i = 0; i < items.Length; i++) { }

// 複雜邏輯務必語意化
foreach (var user in activeUsers)
{
    var userProfile = GetProfile(user.Id);
    // ...
}

8. 成員宣告順序與排版

public class Product
{
    // 1. 常數
    public const int MaxNameLength = 100;

    // 2. 靜態欄位
    private static readonly Logger _logger = LogManager.GetCurrentClassLogger();

    // 3. 實例欄位
    private string _productId;
    private decimal _price;

    // 4. 建構函式
    public Product(string productId) { _productId = productId; }

    // 5. 公用屬性
    public string ProductId => _productId;
    public decimal Price { get => _price; set => _price = value; }

    // 6. 公用方法
    public void ApplyDiscount(decimal percent) { }

    // 7. 私有方法
    private void ValidatePrice() { }
}

9. using 指令分組排序

// 系統命名空間
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

// 第三方套件
using Newtonsoft.Json;
using NLog;

// 專案內部
using MyProject.Domain;
using MyProject.Infrastructure;

10. 檔案與目錄結構對應命名空間

  • 單一檔案通常只包含一個公用類別,檔名與類別名同名 (如 `Product.cs`)。
  • 目錄階層對應命名空間層級:`MyProject/Domain/Entities/Product.cs` → `namespace MyProject.Domain.Entities`。

11. 大括號風格

// C# 慣用 Allman 風格 (大括號另起一行)
public class Sample
{
    public Sample()
    {
        // TODO
    }
}

工具自動化強制規範

  • .editorconfig:專案根目錄加入,定義 `dotnet_naming_rule.*`、`csharp_style_*` 等規則,IDE 即時提示。
  • StyleCop.Analyzers / Roslyn Analyzers:建置時強制檢查命名、排版、文件註解。
  • dotnet format:CLI 一鍵格式化整個 Solution。

總結

統一的命名規範是程式碼可讀性、可維護性與團隊協作效率的基石。遵循 Microsoft 官方 .NET Design Guidelines 核心原則 (PascalCase/camelCase/_camelCase/I-Prefix/Async-Suffix),並配合 `.editorconfig` 與分析器自動化落地,能讓團隊專注於業務邏輯而非風格爭論。

copyright © 萬盛學電腦網 all rights reserved