.NET 幫助

C# 命名規範(開發者如何使用)

命名約定 是一組開發人員遵循的規則和指導方針,用於一致地命名變數、方法、類別和其他實體。 一致的命名不僅提高了程式碼的可讀性,還有助於其他開發人員理解和維護您的程式碼。 以下我們將逐步介紹C#命名約定,重點放在實際使用和範例上。 讓我們深入探討命名約定及本文稍後將介紹的IronPDF庫

命名規則概覽

類別和介面

類別名稱應遵循 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 大小寫。 屬性應該命名為明確描述它們所代表的內容:

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 的大寫規則不同,因為第一個字母不大寫。

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 前綴後加上事件名稱。 事件處理方法的參數通常包括物件發送者和事件參數。

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

在這種情況下,參數命名為 sender 和 e。 遵循這種命名規範可以使您的事件處理程序與業界標準保持一致。

命名私有字段和物件初始化器

私有字段應遵循駝峰命名規則,但應以底線作為前綴。 這有助於將它們與區域變數和方法參數區分開來。

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

在此範例中,屬性名稱 Balance 和 DateOpened 使用 Pascal 命名法,遵循屬性命名慣例。

異常處理與方法

處理例外時,方法名稱應仍符合 Pascal Case 命名慣例。 例外類別名稱也應採用帕斯卡命名法,並以例外結尾。 例如:

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

使用正確的格式化使代碼更易於閱讀和遵循。

避免匈牙利符號命名法

在現代 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 內容生成 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# 命名慣例(開發人員如何使用):圖 2 - IronPDF 授權頁面

通過遵循這些 C# 命名約定,您可以確保您的代碼清晰、易讀且易於維護。 無論是對類名使用帕斯卡命名法、對局部變量使用駝峰式命名法,還是對私有欄位使用下劃線前綴,這些慣例都有助於建立一致的代碼庫。

使用 IronPDF,您可以立即開始探索其所有功能,並享受免費試用。 此試用版讓您親自體驗其如何有效整合到您的工作流程中。 當您準備好邁出下一步時,授權起始價格僅為$749。

Chipego
奇佩戈·卡林达
軟體工程師
Chipego 擁有天生的傾聽技能,這幫助他理解客戶問題,並提供智能解決方案。他在獲得信息技術理學學士學位後,于 2023 年加入 Iron Software 團隊。IronPDF 和 IronOCR 是 Chipego 專注的兩個產品,但隨著他每天找到新的方法來支持客戶,他對所有產品的了解也在不斷增長。他喜歡在 Iron Software 的協作生活,公司內的團隊成員從各自不同的經歷中共同努力,創造出有效的創新解決方案。當 Chipego 離開辦公桌時,他常常享受讀好書或踢足球的樂趣。
< 上一頁
C# 可空類型 (開發者如何使用)
下一個 >
C# 初始化列表(開發人員如何運作)