为什么我不建议在C#中用下划线_开头来表示私有字段

Iris ·
更新时间:2024-09-20
· 603 次阅读

我在C#官方文档的使用属性里看到这种代码:

public class Date { private int _month = 7; // Backing store public int Month { get => _month; set { if ((value > 0) && (value < 13)) { _month = value; } } } }

这段代码里的_month是以下划线开头的,用来表示private。这样做会有什么问题呢?

项目混合使用了驼峰命名法与下划线命名法,扰乱了阅读代码的视线 不像其他语言(比如JavaScript),C#本身已经提供了private修饰符,不需要再用下划线_重复表示private 下划线_已经用来表示弃元的功能了,是不是会造成混淆呢?

实际上我简单地使用驼峰命名法,不用下划线_开头,也不会有什么问题。代码如下:

public class Date { private int month = 7; // Backing store public int Month { get => month; set { if ((value > 0) && (value < 13)) { month = value; } } } }

这样看起来更简洁,更容易理解了。下面同样来自官方文档的自动实现的属性里的代码就很不错:

// This class is mutable. Its data can be modified from // outside the class. class Customer { // Auto-implemented properties for trivial get and set public double TotalPurchases { get; set; } public string Name { get; set; } public int CustomerID { get; set; } // Constructor public Customer(double purchases, string name, int ID) { TotalPurchases = purchases; Name = name; CustomerID = ID; } // Methods public string GetContactInfo() { return "ContactInfo"; } public string GetTransactionHistory() { return "History"; } // .. Additional methods, events, etc. } class Program { static void Main() { // Intialize a new object. Customer cust1 = new Customer(4987.63, "Northwind", 90108); // Modify a property. cust1.TotalPurchases += 499.99; } }

事实上,只使用驼峰命名法,不要暴露字段而是使用属性与get/set访问器,或者是单纯地起个更好的变量名,你总是可以找到办法来避免用下划线_开头。


作者:飞翔吧星尘龙



字段 下划线 C#

需要 登录 后方可回复, 如果你还没有账号请 注册新账号