跳至页脚内容
.NET 帮助

C# 命名约定(开发者用法)

命名约定是一套规则和指南,开发人员遵循这些规则来一致地命名变量、方法、类和其他实体。 一致的命名不仅增强代码可读性,还帮助其他开发人员理解和维护你的代码。 下面,我们将逐步讲解 C# 的命名约定,重点关注实际使用和示例。 让我们直接深入讨论命名约定,并在文章后面讨论 IronPDF 库

命名约定概述

类和接口

类名应遵循 Pascal 命名约定。 这意味着名称中的每个单词都以大写字母开头,没有下划线或空格。 接口名称也应遵循 Pascal 命名,但以前缀 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 命名。 I 前缀明确表示 ICustomer 类型是一个接口。

方法

方法名也使用 Pascal 命名。 每个方法名应该以大写字母开头,每个后续单词也应该以大写字母开头。 这里是一些方法定义的例子:

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 命名。

属性

与方法名一样,属性名也使用 Pascal 命名。 属性应命名以明确描述其代表的内容:

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

局部变量和方法参数

局部变量方法参数应使用小驼峰命名。 这意味着第一个单词是小写的,后续单词以大写字母开头,没有空格或下划线。 这与 Pascal 命名的不同之处在于第一个字母不大写。

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

静态成员和字段

类中的静态成员,如 静态字段常量方法,也遵循特定的命名约定。

静态字段

对于静态字段,命名约定是使用小驼峰命名但带有下划线前缀。 这将它们与其他字段区分开来。

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 命名,遵循属性的命名约定。

异常处理和方法

处理异常时,方法名称仍应遵循 Pascal 命名约定。 异常类名称应为 Pascal 命名,并以 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 命名约定。

C# 常量命名约定

在 C# 中,常量名称应为全大写字母,单词之间用下划线分隔。 这使常量从其他变量中脱颖而出。 以下是一个例子:

public const double PI = 3.14159;
public const double PI = 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;
    }
}
$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; }
$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();
    }
}
$vbLabelText   $csharpLabel

通过坚持这些命名约定,你的代码在使用 IronPDF 生成报告时保持专业、组织和易读。

结论

C# 命名约定(对开发者的工作方式):图 2 - IronPDF 许可页面

通过遵循这些 C# 命名约定,确保你的代码整洁、可读且易于维护。 无论是类名使用 Pascal 命名,局部变量使用小驼峰命名,还是私有字段使用下划线前缀,这些约定有助于建立一致的代码库。

借助 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# 中私人字段应遵循哪些命名约定?

C# 中的私有字段应使用带有下划线前缀的驼峰命名法。这有助于将其与局部变量和方法参数区分开。

命名约定怎样让 C# 开发人员受益?

命名约定提高了代码的可读性和可维护性,使开发人员更容易理解和使用代码。在 C# 项目中,包括使用 IronPDF 的项目中,保持一致的命名有助于确保代码库专业整洁。

Jacob Mellor,Team Iron 的首席技术官
首席技术官

Jacob Mellor 是 Iron Software 的首席技术官,是 C# PDF 技术的先锋工程师。作为 Iron Software 核心代码库的原始开发者,自公司成立以来,他就塑造了公司的产品架构,并与首席执行官 Cameron Rimington 一起将其转变成一家公司,拥有50多人,服务于 NASA、特斯拉和全球政府机构。

Jacob 拥有曼彻斯特大学 (1998-2001) 的一级荣誉土木工程学士学位。1999 年在伦敦创办了自己的第一家软件公司,并于 2005 年创建了他的第一个 .NET 组件后,他专注于解决微软生态系统中的复杂问题。

他的旗舰 IronPDF 和 Iron Suite .NET 库在全球已获得超过 3000 万次的 NuGet 安装,其基础代码继续为全球使用的开发者工具提供支持。拥有 25 年商业经验和 41 年编程经验的 Jacob 仍专注于推动企业级 C#、Java 和 Python PDF 技术的创新,同时指导下一代技术领导者。