跳過到頁腳內容
.NET幫助

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

命名規則 是開發人員用來一致地命名變量、方法、類和其他實體的一系列規則和指南。 一致的命名不僅能提高代碼的可讀性,還有助於其他開發人員理解和維護你的代碼。 下面,我們將逐步講解 C# 命名規範,重點關注實際應用和例子。 讓我們直接深入命名規則,並在文章後面討論 IronPDF 庫

命名規範概述

類和接口

類名應遵循帕斯卡命名法。 這意味著名稱中的每個單詞都以大寫字母開頭,沒有下劃線或空格。 接口名稱也應遵循帕斯卡命名法,但應以前綴 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 都遵循帕斯卡命名法。 I 前綴明確表明 ICustomer 類型是接口。

方法

方法名也使用帕斯卡命名法。 每個方法名應該以大寫字母開始,隨後的每個單詞也應該以大寫字母開始。 這裡是一個方法定義的例子:

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(),約定是相同的——對方法名使用帕斯卡命名法。

屬性

像方法名一樣,屬性名也使用帕斯卡命名法。 屬性應該命名為明確描述它們所代表的內容:

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

局部變量和方法參數

局部變量方法參數應使用駝峰命名法。 這意味著第一個單詞是小寫的,隨後的單詞以大寫字母開始,沒有空格或下劃線。 這與帕斯卡命名法不同,因為第一個字母不大寫。

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

靜態成員和字段

類中的靜態成員,如靜態字段常量方法,也遵循特定的命名規範。

靜態字段

對於靜態字段,命名規範是使用駝峰命名法,但帶有下劃線前綴。 這將它們與其他字段區分開來。

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 使用帕斯卡命名法,遵循屬性命名規範。

異常處理和方法

在處理異常時,方法名稱應仍遵循帕斯卡命名法。 異常類名也應使用帕斯卡命名法並以異常後綴結尾。 例如:

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 是描述性的,並遵循帕斯卡命名規範。

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

使用適當的格式使代碼更易於閱讀和跟隨。

避免使用匈牙利符號

在現代 C# 開發中,匈牙利符號(例如,用數據類型前綴變量名稱,如 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# 命名規範(如何適用於開發人員):圖 1 - IronPDF:C# PDF 庫

當將 IronPDF 整合到你的 C# 項目中時,遵循命名規範以維護清晰、可讀的代碼是很重要的。 IronPDF 允許你在 C# 應用中從 HTML 內容生成 PDFs。 在此過程中,遵循類、方法和變量的命名規範以保持一致性是重要的。 以下是一個簡單實施命名規範的例子,以提高使用 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# 命名規範(如何適用於開發人員):圖 2 - IronPDF 許可頁面

遵循這些 C# 命名規範,你可以確保代碼乾淨、可讀且易於維護。 無論是對類名使用帕斯卡命名法、對局部變量使用駝峰命名法,還是對私有字段使用下劃線前綴,這些規範都有助於建立一致的代碼庫。

使用 IronPDF,你可以立即探索它的所有功能,使用 免費試用。 此試用讓你親自實驗並看一看它如何很好地融入你的工作流程。 當你準備好邁出下一步時,許可證起價僅 $799。

常見問題解答

什麼是 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# 項目中,保持一致的命名以確保專業且清晰的代碼庫。

Curtis Chau
技術作家

Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。

除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。