跳過到頁腳內容
.NET HELP

C# Naming Conventions (How It Works For Developers)

命名慣例是開發人員為了一致地命名變數、方法、類別和其他實體而遵循的一系列規則和準則。 一致的命名方式不僅能增強程式碼的可讀性,還能幫助其他開發人員理解並維護您的程式碼。 以下,我們將逐步介紹 C# 命名慣例,並重點介紹實際用法和範例。 讓我們在稍後的文章中直接討論命名慣例和 IronPDF 函式庫

命名慣例概述

類別與介面

類別名稱應遵循 Pascal Case 命名慣例。 這表示名稱中的每個字都要以大寫字母開頭,不能有下劃線或空格。 介面名稱也應遵循 Pascal Case,但以前綴 I 開頭。 舉例來說

public class Customer
{
    public decimal Balance { get; set; }
}

public interface ICustomer
{
    decimal GetBalance();
}
public class Customer
{
    public decimal Balance { get; set; }
}

public interface ICustomer
{
    decimal GetBalance();
}
$vbLabelText   $csharpLabel

請注意類別名稱 Customer 和介面名稱 ICustomer 皆遵循 Pascal Case。 I 前綴清楚說明 ICustomer 類型是一個介面。

方法

方法名稱也使用 Pascal Case。 每個方法名稱都應以大寫字母開頭,接下來的每個單字也應以大寫字母開頭。 以下是方法定義的範例:

public decimal CalculateInterest(decimal principal, decimal rate)
{
    return principal * rate;
}
public decimal CalculateInterest(decimal principal, decimal rate)
{
    return principal * rate;
}
$vbLabelText   $csharpLabel

對於入口點方法,static void Main() 的慣例是相同的,方法名稱使用 Pascal Case。

屬性

與方法名稱一樣,屬性名稱也使用 Pascal Case。 屬性的命名應清楚說明其代表的意義:

public DateTime DateOpened { get; set; }
public decimal Reserves { get; set; }
public DateTime DateOpened { get; set; }
public decimal Reserves { get; set; }
$vbLabelText   $csharpLabel

本地變數和方法參數

本地變數方法參數應使用駝峰大小寫。 這表示第一個單字以小楷開頭,接下來的單字以大寫字母開頭,沒有空格或下劃線。 這與 Pascal Case 的不同之處在於首字母不大楷。

public void SelectCustomer(string customerName)
{
    var selectedCustomer = FindCustomer(customerName);
}
public void SelectCustomer(string customerName)
{
    var selectedCustomer = FindCustomer(customerName);
}
$vbLabelText   $csharpLabel

在這個範例中,局部變數 selectedCustomer 遵循駱駝式大小寫慣例,而方法參數 customerName 也是駱駝式大小寫。

方法論據

方法參數的名稱應具有描述性,並遵循駱駝紋命名慣例。 這可提高程式碼的可讀性,並協助開發人員瞭解每個參數所代表的意義。

public void AddCustomer(string customerName, DateTime dateOpened)
{
    // Add customer logic
}
public void AddCustomer(string customerName, DateTime dateOpened)
{
    // Add customer logic
}
$vbLabelText   $csharpLabel

靜態成員與欄位

類中的靜態成員,如 靜態欄位常量方法,也遵循特定的命名慣例。

靜態字段

對於 靜態欄位,命名慣例是使用駝峰大小寫,但要加上 underscore前綴。 這樣才能區別於其他領域。

private static int _totalCustomers;
private static int _totalCustomers;
$vbLabelText   $csharpLabel

常數

常數通常使用 全大楷字母命名,並以下劃線分隔字詞,以提高可讀性。 舉例來說

public const int MAX_CUSTOMERS = 100;
public const int MAX_CUSTOMERS = 100;
$vbLabelText   $csharpLabel

事件處理程式

事件處理器方法名稱應描述其處理的事件,通常使用 On 前綴,後跟事件名稱。 事件處理器方法的參數通常包括物件 sender 和事件參數。

private void OnCustomerAdded(object sender, EventArgs e)
{
    // Event handling logic
}
private void OnCustomerAdded(object sender, EventArgs e)
{
    // Event handling logic
}
$vbLabelText   $csharpLabel

在本例中,參數被命名為 sendere 。 遵循此命名慣例可使您的事件處理程式符合業界標準。

命名私有欄位和物件初始化器

私人欄位應遵循駱駝紋大小寫慣例,但要有下划線前綴。 這有助於將它們與局部變數和方法參數區分開來。

private string _customerName;
private string _customerName;
$vbLabelText   $csharpLabel

使用 物件初始化器時,您可以在建立類別的實體時直接為屬性指定值:

var seattleCustomer = new Customer
{
    Balance = 1000,
    DateOpened = DateTime.Now
};
var seattleCustomer = new Customer
{
    Balance = 1000,
    DateOpened = DateTime.Now
};
$vbLabelText   $csharpLabel

在這個範例中,屬性名稱 BalanceDateOpened 採用 Pascal Case,遵循屬性的慣例。

異常處理與方法

在處理異常時,方法名稱仍應遵循 Pascal Case 慣例。 Exception 類別名稱也應使用 Pascal Case,並以後綴 Exception 結尾。 舉例來說

public void ProcessTransaction()
{
    try
    {
        // Transaction logic
    }
    catch (InvalidOperationException ex)
    {
        // Handle exception
    }
}
public void ProcessTransaction()
{
    try
    {
        // Transaction logic
    }
    catch (InvalidOperationException ex)
    {
        // Handle exception
    }
}
$vbLabelText   $csharpLabel

返回類型和方法定義

務必確保您的 方法定義具有有意義的名稱和適當的回傳類型。回傳類型應從方法簽章中清楚顯示。 以下是一個範例:

public decimal CalculateTotalBalance()
{
    return _totalCustomers * balancePerCustomer;
}
public decimal CalculateTotalBalance()
{
    return _totalCustomers * balancePerCustomer;
}
$vbLabelText   $csharpLabel

在這個範例中,方法名稱 CalculateTotalBalance 是描述性的,並遵循 Pascal Case 命名慣例。

C# 常數的命名慣例

在 C# 中,常數名稱應為全大楷字母,並以下劃線分隔字詞。 這讓常數從其他變數中脫穎而出。 以下是一個範例:

public const double PI = 3.14159;
public const double PI = 3.14159;
$vbLabelText   $csharpLabel

此慣例適用於不同類型,可確保 常規名稱在程式碼中一致且易於辨識。

C# 斷行和括號的編碼慣例

C# 也有換行符括號編碼慣例。 在 C# 中,每個開頭的 brace { 應該與它所屬的語句在同一行,而結尾的 brace } 應該在新的一行,並與對應的語句對齊。 以下是一個範例:

public void AddCustomer(string customerName)
{
    if (!string.IsNullOrEmpty(customerName))
    {
        _customerName = customerName;
    }
}
public void AddCustomer(string customerName)
{
    if (!string.IsNullOrEmpty(customerName))
    {
        _customerName = customerName;
    }
}
$vbLabelText   $csharpLabel

使用適當的格式可讓程式碼更容易閱讀和遵循。

避免使用匈牙利語 Notation

在現代 C# 開發中,不鼓勵使用 Hungarian Notation,即變數名稱以資料類型為前綴(例如,strName 表示字串,intCount 表示整數)。 相反,請使用 有意義的名稱,描述變數的用途而非其資料類型:

public string CustomerName { get; set; }
public int OrderCount { get; set; }
public string CustomerName { get; set; }
public int OrderCount { get; set; }
$vbLabelText   $csharpLabel

此方法可使程式碼更清晰、更易維護。

使用命名慣例的 IronPDF

C# 命名慣例 (How It Works For Developers):圖 1 - IronPDF:C# PDF Library

IronPDF 整合至 C# 專案時,必須遵循命名慣例,以維持程式碼的乾淨、可讀性。 IronPDF 可讓您在 C# 應用程式中從 HTML 內容產生 PDF。 在這樣做的同時,必須遵循類別、方法和變數的命名慣例,以維持一致性。 以下是一個簡單實現命名慣例的範例,在遵守這些命名慣例的同時,使用 IronPDF 增強代碼的可讀性:

using IronPdf;

public class PdfReportGenerator
{
    private readonly string _htmlContent;
    private readonly string _filePath;

    public PdfReportGenerator(string htmlContent, string filePath)
    {
        _htmlContent = htmlContent;
        _filePath = filePath;
    }

    public void GenerateReport()
    {
        var pdfRenderer = new ChromePdfRenderer();
        PdfDocument pdfDocument = pdfRenderer.RenderHtmlAsPdf(_htmlContent);
        pdfDocument.SaveAs(_filePath);
    }
}

public static class Program
{
    public static void Main()
    {
        var htmlContent = "<h1>Monthly Report</h1><p>Generated using IronPDF.</p>";
        var filePath = @"C:\Reports\MonthlyReport.pdf";
        PdfReportGenerator reportGenerator = new PdfReportGenerator(htmlContent, filePath);
        reportGenerator.GenerateReport();
    }
}
using IronPdf;

public class PdfReportGenerator
{
    private readonly string _htmlContent;
    private readonly string _filePath;

    public PdfReportGenerator(string htmlContent, string filePath)
    {
        _htmlContent = htmlContent;
        _filePath = filePath;
    }

    public void GenerateReport()
    {
        var pdfRenderer = new ChromePdfRenderer();
        PdfDocument pdfDocument = pdfRenderer.RenderHtmlAsPdf(_htmlContent);
        pdfDocument.SaveAs(_filePath);
    }
}

public static class Program
{
    public static void Main()
    {
        var htmlContent = "<h1>Monthly Report</h1><p>Generated using IronPDF.</p>";
        var filePath = @"C:\Reports\MonthlyReport.pdf";
        PdfReportGenerator reportGenerator = new PdfReportGenerator(htmlContent, filePath);
        reportGenerator.GenerateReport();
    }
}
$vbLabelText   $csharpLabel

堅持使用這些命名慣例,您的程式碼就能保持專業、有條理,並在使用 IronPDF 生成報告時易於閱讀。

結論

C# 命名慣例 (How It Works For Developers):圖 2 - IronPDF 授權頁面

只要遵循這些 C# 命名慣例,就能確保您的程式碼乾淨、易讀且容易維護。 無論是使用 Pascal Case 來表示類別名稱、使用 camel case 來表示局部變數,或是使用 underscore 前綴來表示私有欄位,這些慣例都有助於建立一致的程式碼基礎。

有了 IronPdf,您可以透過 免費試用,立即加入並探索其所有功能。 此試用版可讓您進行實驗,親自瞭解它與您的工作流程的整合程度。 當您準備好採取下一步時,授權起始價格僅為 $799 。

常見問題解答

C# 中類別和介面的一般命名慣例是什麼?

在 C# 中,類別和介面應該使用 Pascal Case 來命名,每個字都以大寫字母開頭。介面也應包含 'I「 前綴,例如 」ICustomer'。

如何確保 C# 中的方法名稱符合最佳實務?

C# 中的方法名稱應遵循 Pascal Case 慣例,每個單字以大寫字母開頭。此慣例適用於所有方法,包括入口點方法 Main

在 C# 中命名局部變數的建議方式是什麼?

C# 中的局部變數和方法參數應該使用 camel case 來命名,也就是第一個字是小寫,接下來的每個字以大寫字母開頭。

C# 中的靜態欄位應該如何命名?

C# 中的靜態欄位應使用駱駝紋大小寫命名,並加上下劃線前綴,以區別於其他欄位。

C# 中常數的命名慣例是什麼?

C# 中的常量應使用全大楷字母命名,並以下劃線分隔,使其易於區分。

如何在遵守 C# 命名慣例的同時使用函式庫?

使用 IronPDF 等 C# 程式庫時,請遵循命名慣例,以維持程式碼的乾淨、可讀性。這包括對類和方法使用 Pascal Case,對變數則使用 camel case。例如,您可以使用 IronPDF 從 HTML 生成 PDF,同時保持一致的命名慣例。

為何在 C# 中不推薦使用 Hungarian Notation?

在現代 C# 開發中不鼓勵使用 Hungarian Notation,因為它會使程式碼的可讀性降低。取而代之的是,使用有意義的名稱來描述變數的目的,並遵守既定的命名慣例。

C# 中應該如何命名事件處理器方法?

C# 中的事件處理器方法應命名為描述其處理的事件,通常使用 'On' 前綴,後跟事件名稱。這有助於闡明方法的目的。

C# 中的私有欄位應遵循哪些命名慣例?

C# 中的私有欄位應該使用帶下划線前綴的駝峰大小寫來命名。這有助於區別它們與局部變數和方法參數。

命名慣例如何讓 C# 開發人員獲益?

命名慣例可增強程式碼的可讀性和可維護性,讓開發人員更容易理解和使用程式碼。C# 專案(包括使用 IronPDF 等函式庫的專案)中一致的命名方式可確保代碼庫的專業性和整潔性。

Jacob Mellor,技術長 @ Team Iron
首席技術長

Jacob Mellor 是 Iron Software 的首席技術長,也是開創 C# PDF 技術的有遠見的工程師。作為 Iron Software 核心程式碼庫背後的原始開發人員,他從公司成立之初就塑造了公司的產品架構,與首席執行官 Cameron Rimington 一起將公司轉型為一家 50 多人的公司,為 NASA、Tesla 和全球政府機構提供服務。

Jacob 持有曼徹斯特大學土木工程一級榮譽工程學士學位 (BEng)(1998-2001 年)。

Jacob 於 1999 年在倫敦開設了他的第一家軟體公司,並於 2005 年創建了他的第一個 .NET 元件,之後,他專門解決微軟生態系統中的複雜問題。

他的旗艦產品 IronPDF & Iron Suite for .NET 函式庫在全球的 NuGet 安裝量已超過 3000 萬次,他的基礎程式碼持續為全球使用的開發人員工具提供動力。Jacob 擁有 25 年的商業經驗和 41 年的編碼專業知識,他一直專注於推動企業級 C#、Java 和 Python PDF 技術的創新,同時指導下一代的技術領導者。