20 KiB
20 KiB
1.1 命名风格
1. 通用命名原则
-
使用有意义且可读的名称
// ❌ 不建议:缩写和无意义的名称 var d = DateTime.Now; var usr = new User(); int n = 100; // ✅ 建议:清晰表达意图 var currentDate = DateTime.Now; var newUser = new User(); int maxRetryCount = 100; -
不建议使用拼音和中文
// ❌ 不建议 var yongHu = new User(); string xingMing = "张三"; var keHuMingCheng = "张三"; var 订单数量 = 10; // ✅ 建议 var user = new User(); string fullName = "张三"; -
不建议过度缩写
// ❌ 不建议 var cSvc = new CustomerService(); var ordMgr = new OrderManager(); // ✅ 建议 var customerService = new CustomerService(); var orderManager = new OrderManager(); // ✅ 可接受含义广为人知的缩写 var customerId = 1; // Id var htmlContent = ""; // Html var xmlDocument = ""; // Xml var urlAddress = ""; // Url var httpClient = new HttpClient(); // Http -
不建议使用下划线开头(除私有字段外)
// ❌ 不建议 public string _customerName; public void _ProcessOrder() { } // ✅ 建议 public string CustomerName { get; set; } private string _customerName; // 私有字段可以使用 public void ProcessOrder() { }
2. 命名约定
2.1 类
-
使用 PascalCase(帕斯卡命名法)
// ✅ 建议的类命名 public class Customer { } public class OrderService { } public class ProductRepository { } public class PaymentProcessor { } -
使用名词或名词短语
// ✅ 建议:名词形式 public class Invoice { } public class ShoppingCart { } public class UserProfile { } public class EmailValidator { } public class UserAuthentication { } // ❌ 不建议:动词形式 public class ProcessOrder { } // 应该是 OrderProcessor public class ValidateUser { } // 应该是 UserValidator public class Calculate { } // 适用于方法命名 -
建议的命名方式
// 服务类 // ✅ 以 Service 结尾 public class CustomerService { } public class EmailService { } // ✅ 以职责命名 public class OrderProcessor { } public class EmailSender { } public class PaymentGateway { } public class CacheManager { } // 仓储类 // ✅ 以 Repository 结尾 public class OrderRepository { } public class ProductRepository { } // ✅ Provider public class AuthenticationProvider { } public class DataProvider { } // ✅ Helper/Utility public class StringHelper { } public class DateTimeUtility { } // 异常类 // ✅ 以 Exception 结尾 public class OrderNotFoundException { } public class InvalidOperationException { } // ✅ Attribute public class ValidateAttribute { } public class AuthorizeAttribute { } // ✅ DTO/ViewModel public class CustomerDto { } public class OrderViewModel { } public class CreateProductRequest { } public class ProductResponse { } public class DoSomethingInput { } public class DoSomethingOutput { } // ✅ Entity/Model public class Order { } public class Product { } public class Customer { } // 验证器 // ✅ 以 Validator 结尾 public class OrderValidator { } public class EmailValidator { } public class CreateOrderRequestValidator { } -
不建议的命名方式
// ❌ 不建议:使用下划线或特殊字符 public class Order_Service { } public class Product$Manager { } // ❌ 不建议:使用前缀 public class COrder { } public class TCustomer { } // ❌ 不建议:过于通用 public class Data { } public class Info { } public class Manager { } // 太宽泛,应该是具体的 xxxManager
2.2 接口
-
使用
I前缀 + PascalCase// ✅ 正确的接口命名 public interface ICustomerService { } public interface IOrderRepository { } public interface IPaymentProcessor { } public interface ILogger { } -
使用名词、名词短语或形容词
// ✅ 建议:名词 (一般表示为业务接口) public interface IRepository<T> { } public interface IValidator { } public interface IOrderService { } public interface ILogger { } public interface ICache { } // ✅ 建议:形容词(一般表示为能力接口) public interface IComparable { } public interface IDisposable { } public interface IEnumerable { } public interface IQueryable { } // ✅ 建议:名词短语 public interface IDataAccess { } public interface IUserAuthentication { } -
避免使用 Interface 后缀
// ❌ 不建议 public interface IOrderServiceInterface { } // ✅ 建议 public interface IOrderService { }
2.3 方法
-
使用 PascalCase
public class CustomerService { // ✅ 建议 public void CreateCustomer() { } public Customer GetCustomerById(int id) { } public void UpdateCustomerProfile() { } public void DeleteCustomer() { } } -
使用动词或动词短语
// ✅ 建议:明确、清晰的动作 public void CreateOrder() { } public void UpdateCustomer() { } public void DeleteProduct() { } public Order GetOrderById(int id) { } public List<Order> GetOrdersByCustomer(int customerId) { } public bool ValidateEmail(string email) { } public decimal CalculateDiscount(Order order) { } // ❌ 不建议:名词形式 public void Order() { } // 应该是 CreateOrder 或 ProcessOrder public void Customer() { } -
常用动词前缀
// Get - 获取数据(通常有返回值) public Customer GetCustomerById(int id) { } public List<Order> GetOrders() { } // Find - 查找数据(可能返回 null) public Customer? FindCustomerByEmail(string email) { } // Create/Add - 创建新对象 public void CreateOrder(Order order) { } public void AddProduct(Product product) { } // Update/Modify - 更新现有对象 public void UpdateCustomer(Customer customer) { } public void ModifyOrderStatus(int orderId, OrderStatus status) { } // Delete/Remove - 删除对象 public void DeleteOrder(int orderId) { } public void RemoveProduct(int productId) { } // Save - 保存(创建或更新) public void SaveCustomer(Customer customer) { } // Validate - 验证 public bool ValidateOrder(Order order) { } public ValidationResult ValidateInput(string input) { } // Calculate/Compute - 计算 public decimal CalculateTotal(List<OrderItem> items) { } public int ComputeAge(DateTime birthDate) { } // Process/Handle - 处理 public void ProcessOrder(Order order) { } public void ProcessPayment(Payment payment) { } // 布尔判断 // ✅ 建议: 使用 Is、Has、Can、Should 等前缀更能提高可读性 public bool IsValid() { } public bool IsActive() { } public bool HasPermission() { } public bool CanProcess() { } public bool ShouldRetry() { } public bool Exists(int id) { } public bool Contains(string value) { } // ❌ 不建议:不清晰的命名 public bool Valid() { } public bool Active() { } public bool Permission() { } // Convert/Transform - 转换 public OrderDto ConvertToDto(Order order) { } public string TransformToJson(object obj) { } // Send/Receive - 发送/接收 public void SendNotification(string message) { } public Message ReceiveMessage() { } `` -
常用查询方法命名方式
// ✅ 单个对象 public Customer GetCustomerById(int id) { } public Order FindOrderByNumber(string orderNumber) { } // ✅ 集合 public List<Customer> GetAllCustomers() { } public IEnumerable<Order> GetOrdersByCustomer(int customerId) { } public List<Product> FindProductsByCategory(string category) { } // ✅ 条件查询 public List<Order> GetActiveOrders() { } public List<Customer> GetVipCustomers() { } // ✅ 分页查询 public PagedResult<Product> GetProducts(int pageIndex, int pageSize) { } public List<Order> GetOrdersByPage(int pageNumber, int pageSize) { } -
私有方法也应该使用 PascalCase
public class OrderProcessor { // ✅ 私有方法也使用 PascalCase private void ValidateOrderItems(Order order) { } private decimal CalculateItemTotal(OrderItem item) { } private bool CheckInventory(int productId) { } }
2.4 属性与字段
-
属性使用 PascalCase
public class Customer { // ✅ 建议的属性命名 public int Id { get; set; } public string Name { get; set; } public string Email { get; set; } public DateTime CreatedDate { get; set; } public bool IsActive { get; set; } public decimal TotalAmount { get; set; } } -
私有字段使用 _camelCase
public class OrderService { // ✅ 建议的私有字段命名 private readonly IOrderRepository _orderRepository; private readonly ILogger<OrderService> _logger; private readonly IEmailService _emailService; private int _retryCount; private bool _isProcessing; } -
只读字段
public class Configuration { // ✅ 公共只读字段使用 PascalCase public readonly string DefaultCulture = "zh-CN"; //(公共只读字段建议改为属性方式使用) // ✅ 私有只读字段使用 _camelCase private readonly string _connectionString; private readonly int _maxRetryCount; } -
静态字段
public class AppConstants { // ✅ 公共静态字段使用 PascalCase public static readonly int MaxPageSize = 100; public static readonly string DefaultDateFormat = "yyyy-MM-dd"; // ✅ 私有静态字段使用 _camelCase private static readonly object _lockObject = new object(); } -
布尔属性
public class Order { // ✅ 建议使用 Is、Has、Can 等前缀提高可读性 public bool IsCompleted { get; set; } public bool IsPaid { get; set; } public bool HasDiscount { get; set; } public bool CanBeCancelled { get; set; } // ❌ 不建议 public bool Completed { get; set; } public bool Paid { get; set; } } -
集合属性
public class Order { // ✅ 建议:使用复数形式 public List<OrderItem> Items { get; set; } public ICollection<Payment> Payments { get; set; } public IEnumerable<Comment> Comments { get; set; } // ❌ 不建议:使用单数 public List<OrderItem> Item { get; set; } }
2.5 变量与参数
-
局部变量使用 camelCase
public void ProcessOrder(int orderId) { // ✅ 建议的局部变量命名 var order = GetOrder(orderId); var totalAmount = CalculateTotal(order); var discountRate = GetDiscountRate(order); var finalPrice = totalAmount * (1 - discountRate); var isValid = ValidateOrder(order); } -
方法参数使用 camelCase
// ✅ 建议的参数命名 public Order CreateOrder(int customerId, List<OrderItem> items, decimal discountAmount, string shippingAddress) { // ...existing code... } // ✅ 布尔参数命名 public List<Order> GetOrders(int customerId, bool includeCompleted, bool includeCancelled) { // ...existing code... } -
循环变量命名
// ✅ 简单循环可以使用单字母 for (int i = 0; i < orders.Count; i++) { // ...existing code... } // ✅ 有意义的循环变量 foreach (var order in orders) { ProcessOrder(order); } foreach (var item in order.Items) { ValidateItem(item); } // ❌ 不建议:不清晰的变量名 foreach (var o in orders) // o 不如 order 清晰 { // ...existing code... } -
LINQ 查询变量命名
// ✅ 建议 var activeCustomers = customers .Where(c => c.IsActive) .ToList(); var customerOrders = orders .Where(o => o.CustomerId == customerId) .OrderByDescending(o => o.CreatedDate) .ToList(); // ✅ 建议:复杂查询使用有意义的变量 var highValueOrders = orders .Where(order => order.TotalAmount > 1000) .Select(order => new { OrderId = order.Id, CustomerName = order.Customer.Name, TotalAmount = order.TotalAmount }) .ToList(); -
临时变量命名
public decimal CalculateOrderTotal(Order order) { // ✅ 建议:清晰的临时变量 var subtotal = order.Items.Sum(item => item.Price * item.Quantity); var taxAmount = subtotal * 0.1m; var shippingFee = CalculateShippingFee(order); var discountAmount = CalculateDiscount(order, subtotal); var total = subtotal + taxAmount + shippingFee - discountAmount; return total; } -
避免使用无意义的变量名
// ❌ 不建议 var temp = GetCustomer(); var data = ProcessData(); var obj = CreateObject(); var result = DoSomething(); // ✅ 建议 var customer = GetCustomer(); var processedOrders = ProcessOrders(); var paymentRecord = CreatePaymentRecord(); var validationResult = ValidateInput();
2.6 常量与枚举
-
常量命名
// ✅ 方式一:PascalCase(推荐) public class OrderConstants { public const int MaxItemsPerOrder = 100; public const decimal MinOrderAmount = 10.0m; public const string DefaultCurrency = "CNY"; } // ✅ 方式二:UPPER_CASE(C# 中较少使用) public class AppSettings { public const int MAX_RETRY_COUNT = 3; public const string DEFAULT_CULTURE = "zh-CN"; } // ✅ 私有常量 private const int MaxRetryAttempts = 3; private const string ErrorMessageTemplate = "处理订单 {0} 时发生错误"; -
枚举命名
// ✅ 枚举类型使用 PascalCase,单数形式 public enum OrderStatus { Pending, // 枚举值使用 PascalCase Processing, Completed, Cancelled, Refunded } // ✅ 标志枚举使用复数 [Flags] public enum UserPermissions { None = 0, Read = 1, Write = 2, Delete = 4, Admin = 8 } // ❌ 不建议:使用复数(非标志枚举) public enum OrderStatuses { } // ❌ 不建议:枚举值使用前缀 public enum OrderStatus { OrderStatusPending, // 不需要前缀 OrderStatusCompleted } -
常量类组织
// ✅ 按功能组织常量 public static class ValidationConstants { public const int MinPasswordLength = 8; public const int MaxPasswordLength = 50; public const int MinUsernameLength = 3; public const int MaxUsernameLength = 20; } public static class CacheKeys { public const string CustomerPrefix = "customer_"; public const string OrderPrefix = "order_"; public const string ProductPrefix = "product_"; } public static class ErrorCodes { public const string OrderNotFound = "ORDER_NOT_FOUND"; public const string InsufficientStock = "INSUFFICIENT_STOCK"; public const string PaymentFailed = "PAYMENT_FAILED"; }
2.7 布尔类型
-
使用肯定的命名方式
// ✅ 建议:肯定形式 public bool IsActive { get; set; } public bool IsEnabled { get; set; } public bool HasPermission { get; set; } public bool CanEdit { get; set; } // ❌ 不建议:否定形式(增加理解难度) public bool IsNotActive { get; set; } public bool IsDisabled { get; set; } -
常用布尔命名前缀
public class Order { // Is - 状态判断 public bool IsCompleted { get; set; } public bool IsValid { get; set; } public bool IsPaid { get; set; } // Has - 拥有判断 public bool HasDiscount { get; set; } public bool HasShipped { get; set; } // Can - 能力判断 public bool CanBeCancelled { get; set; } public bool CanBeRefunded { get; set; } // Should - 应该判断 public bool ShouldSendEmail { get; set; } public bool ShouldApplyDiscount { get; set; } } -
布尔方法命名
public class OrderValidator { // ✅ 建议 public bool IsValidOrder(Order order) { } public bool HasSufficientStock(int productId, int quantity) { } public bool CanProcessPayment(Payment payment) { } public bool Exists(int orderId) { } // ✅ 验证方法也可以使用 Validate 开头,返回 bool public bool ValidateOrderItems(Order order) { } }
2.8 集合类型
-
使用复数形式
public class Customer { // ✅ 建议:使用复数 public List<Order> Orders { get; set; } public ICollection<Address> Addresses { get; set; } public IEnumerable<Payment> Payments { get; set; } // ❌ 不建议 public List<Order> OrderList { get; set; } // 不需要 List 后缀 public List<Order> Order { get; set; } // 应使用复数 } -
集合局部变量命名
public void ProcessOrders() { // ✅ 建议 var orders = GetOrders(); var activeOrders = orders.Where(o => o.IsActive).ToList(); var orderIds = orders.Select(o => o.Id).ToList(); var customerNames = customers.Select(c => c.Name).ToList(); // ❌ 不建议 var orderDictionary = orders.ToDictionary(o => o.Id); var customersByEmail = customers.ToDictionary(c => c.Email); } -
特殊集合命名
// ✅ 字典 private readonly Dictionary<int, Order> _orderCache; private readonly ConcurrentDictionary<string, Customer> _customerLookup; // ✅ 队列 private readonly Queue<OrderMessage> _orderQueue; private readonly ConcurrentQueue<Task> _taskQueue; // ✅ 堆栈 private readonly Stack<Command> _commandHistory;
2.9 异步方法
-
使用
Async后缀// ✅ 异步方法使用 Async 后缀 public async Task<Order> GetOrderAsync(int orderId) { return await _repository.GetByIdAsync(orderId); } public async Task<List<Order>> GetOrdersAsync(int customerId) { return await _repository.GetOrdersByCustomerAsync(customerId); } public async Task CreateOrderAsync(CreateOrderRequest request) { await _repository.AddAsync(MapToOrder(request)); } public async Task UpdateOrderAsync(Order order) { await _repository.UpdateAsync(order); } public async Task DeleteOrderAsync(int orderId) { await _repository.DeleteAsync(orderId); } -
异步方法返回类型
// ✅ 返回 Task public async Task SendEmailAsync(string to, string subject) { await _emailService.SendAsync(to, subject); } // ✅ 返回 Task<T> public async Task<bool> ValidateOrderAsync(Order order) { return await _validator.ValidateAsync(order); } // ✅ 返回 ValueTask(性能敏感场景) public async ValueTask<int> GetCachedCountAsync() { if (_cache.TryGetValue("count", out int count)) { return count; } return await _repository.GetCountAsync(); } // ❌ 错误:避免使用 async void(除事件处理程序外) public async void ProcessOrderAsync(int orderId) // 错误! { await _service.ProcessAsync(orderId); }