跳過到頁腳內容
.NET幫助

C#命名規則(對開發者如何理解的工作)

命名慣例是開發人員為了一致地命名變數、方法、類別和其他實體而遵循的一系列規則和準則。 一致的命名方式不僅能增強程式碼的可讀性,還能幫助其他開發人員理解並維護您的程式碼。 以下,我們將逐步介紹 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();
}
Public Class Customer
	Public Property Balance() As Decimal
End Class

Public Interface ICustomer
	Function GetBalance() As Decimal
End Interface
$vbLabelText   $csharpLabel

請注意類別名稱 Customer 和介面名稱 ICustomer 都遵循 Pascal 命名法。 I 前綴表明 ICustomer 類型是一個介面。

方法

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

public decimal CalculateInterest(decimal principal, decimal rate)
{
    return principal * rate;
}
public decimal CalculateInterest(decimal principal, decimal rate)
{
    return principal * rate;
}
Public Function CalculateInterest(ByVal principal As Decimal, ByVal rate As Decimal) As Decimal
	Return principal * rate
End Function
$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; }
Public Property DateOpened() As DateTime
Public Property Reserves() As Decimal
$vbLabelText   $csharpLabel

本地變數和方法參數

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

public void SelectCustomer(string customerName)
{
    var selectedCustomer = FindCustomer(customerName);
}
public void SelectCustomer(string customerName)
{
    var selectedCustomer = FindCustomer(customerName);
}
Public Sub SelectCustomer(ByVal customerName As String)
	Dim selectedCustomer = FindCustomer(customerName)
End Sub
$vbLabelText   $csharpLabel

在這個例子中,局部變數selectedCustomer 遵循駝峰命名約定,方法參數customerName 也採用駝峰命名。

方法論據

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

public void AddCustomer(string customerName, DateTime dateOpened)
{
    // Add customer logic
}
public void AddCustomer(string customerName, DateTime dateOpened)
{
    // Add customer logic
}
Public Sub AddCustomer(ByVal customerName As String, ByVal dateOpened As DateTime)
	' Add customer logic
End Sub
$vbLabelText   $csharpLabel

靜態成員與欄位

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

靜態字段

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

private static int _totalCustomers;
private static int _totalCustomers;
Private Shared _totalCustomers As Integer
$vbLabelText   $csharpLabel

常數

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

public const int MAX_CUSTOMERS = 100;
public const int MAX_CUSTOMERS = 100;
Public Const MAX_CUSTOMERS As Integer = 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
}
Private Sub OnCustomerAdded(ByVal sender As Object, ByVal e As EventArgs)
	' Event handling logic
End Sub
$vbLabelText   $csharpLabel

在這種情況下,參數名稱為 sendere。 遵循此命名慣例可使您的事件處理程式符合業界標準。

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

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

private string _customerName;
private string _customerName;
Private _customerName As String
$vbLabelText   $csharpLabel

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

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

在這個例子中,屬性名稱BalanceDateOpened 採用 Pascal 命名法,遵循屬性命名約定。

異常處理與方法

在處理異常時,方法名稱仍應遵循 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
    }
}
Public Sub ProcessTransaction()
	Try
		' Transaction logic
	Catch ex As InvalidOperationException
		' Handle exception
	End Try
End Sub
$vbLabelText   $csharpLabel

返回類型和方法定義

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

public decimal CalculateTotalBalance()
{
    return _totalCustomers * balancePerCustomer;
}
public decimal CalculateTotalBalance()
{
    return _totalCustomers * balancePerCustomer;
}
Public Function CalculateTotalBalance() As Decimal
	Return _totalCustomers * balancePerCustomer
End Function
$vbLabelText   $csharpLabel

在這個例子中,方法名稱CalculateTotalBalance 具有描述性,並且遵循 Pascal Case 命名約定。

C# 常數的命名慣例

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

public const double PI = 3.14159;
public const double PI = 3.14159;
Public Const PI As Double = 3.14159
$vbLabelText   $csharpLabel

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

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

C# 也有換行符括號編碼慣例。 在 C# 中,每個左大括號 {應該與其所屬語句位於同一行,而右大括號 }應該另起一行,與相應的語句對齊。 以下是一個範例:

public void AddCustomer(string customerName)
{
    if (!string.IsNullOrEmpty(customerName))
    {
        _customerName = customerName;
    }
}
public void AddCustomer(string customerName)
{
    if (!string.IsNullOrEmpty(customerName))
    {
        _customerName = customerName;
    }
}
Public Sub AddCustomer(ByVal customerName As String)
	If Not String.IsNullOrEmpty(customerName) Then
		_customerName = customerName
	End If
End Sub
$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; }
Public Property CustomerName() As String
Public Property OrderCount() As Integer
$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();
    }
}
Imports IronPdf

Public Class PdfReportGenerator
	Private ReadOnly _htmlContent As String
	Private ReadOnly _filePath As String

	Public Sub New(ByVal htmlContent As String, ByVal filePath As String)
		_htmlContent = htmlContent
		_filePath = filePath
	End Sub

	Public Sub GenerateReport()
		Dim pdfRenderer = New ChromePdfRenderer()
		Dim pdfDocument As PdfDocument = pdfRenderer.RenderHtmlAsPdf(_htmlContent)
		pdfDocument.SaveAs(_filePath)
	End Sub
End Class

Public Module Program
	Public Sub Main()
		Dim htmlContent = "<h1>Monthly Report</h1><p>Generated using IronPDF.</p>"
		Dim filePath = "C:\Reports\MonthlyReport.pdf"
		Dim reportGenerator As New PdfReportGenerator(htmlContent, filePath)
		reportGenerator.GenerateReport()
	End Sub
End Module
$vbLabelText   $csharpLabel

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

結論

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

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

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

常見問題解答

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

在 C# 中,類別和介面應使用 Pascal 命名法,每個單詞的首字母大寫。介面還應包括 "I" 前綴,例如 'ICustomer'。

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

C# 中的方法名稱應遵循 Pascal 命名法,每個單詞的首字母大寫。此命名法適用於所有方法,包括入口方法 Main

在 C# 中推薦的本地變數命名方式是什麼?

在 C# 中,局部變數和方法參數應使用駝峰式命名,即第一個單詞小寫,隨後的每個單詞首字母大寫。

C# 中靜態字段應如何命名?

在 C# 中,靜態字段應使用駝峰式命名並在前面加上下劃線以區分它們與其他字段。

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

在 C# 中,常數應使用所有大寫字母命名,並用下劃線分隔單詞,這可以使它們易於辨識。

我如何在使用 C# 命名慣例的同時使用庫?

在 C# 中使用庫(如 IronPDF)時,透過遵循命名慣例來保持程式碼的清晰可讀性。這包括對類別和方法使用 Pascal 命名法,對變數使用駝峰式命名。例如,可以使用 IronPDF 從 HTML 生成 PDF,同時保持一致的命名慣例。

為什麼不推薦在 C# 中使用匈牙利命名法?

在現代 C# 開發中不推薦使用匈牙利命名法,因為它可能會使程式碼的可讀性下降。相反,應使用能夠描述變數目的的有意義名稱並遵循已建立的命名慣例。

C# 中的事件處理程序方法應如何命名?

C# 中的事件處理程序方法的命名應描述其處理的事件,通常使用 'On' 前綴,接著是事件名稱。這有助於明確方法的目的。

C# 中 private 字段應遵循哪些命名慣例?

C# 中的 private 字段應使用帶有下劃線前綴的駝峰式命名。這有助於區分它們與局部變數和方法參數。

命名慣例如何使 C# 開發人員受益?

命名慣例提高了程式碼的可讀性和可維護性,使開發人員更容易理解和處理程式碼。在使用如 IronPDF 這樣的庫的 C# 項目中,保持一致的命名以確保專業且清晰的程式碼庫。

Jacob Mellor, Team Iron 首席技術官
首席技術官

Jacob Mellor是Iron Software的首席技術官,也是開創C# PDF技術的前瞻性工程師。作為Iron Software核心代碼庫的原始開發者,他自公司成立以來就塑造了公司的產品架構,並與CEO Cameron Rimington將公司轉型為服務NASA、Tesla以及全球政府機構的50多人公司。

Jacob擁有曼徹斯特大學土木工程一級榮譽學士學位(1998年–2001年)。他於1999年在倫敦開立首家軟體公司,並於2005年建立了他的第一個.NET組件,專注於解決Microsoft生態系統中的複雜問題。

他的旗艦作品IronPDF和Iron Suite .NET程式庫全球已獲得超過3000萬次NuGet安裝,他的基礎代碼不斷在全球各地驅動開發者工具。擁有25年以上的商業經驗和41年的編碼專業知識,Jacob仍然專注於推動企業級C#、Java和Python PDF技術的創新,同時指導下一代技術領導者。

鋼鐵支援團隊

我們每週 5 天,每天 24 小時在線上。
聊天
電子郵件
打電話給我