我常常在一些C#官方文檔的使用屬性裏看到這種代碼:ide
public class Date { private int _month = 7; // Backing store public int Month { get => _month; set { if ((value > 0) && (value < 13)) { _month = value; } } } }
這段代碼裏的_month
是如下劃線開頭的,用來表示private。這樣作會有什麼問題呢?ui
_
重複表示private_
已經用來表示棄元的功能了,是否是形成混淆呢?實際上我簡單地使用駝峯命名法,不用下劃線_
開頭,也不會有什麼問題。代碼以下:code
public class Date { private int month = 7; // Backing store public int Month { get => month; set { if ((value > 0) && (value < 13)) { month = value; } } } }
這樣看起來更簡潔,更容易理解了。下面一樣來自官方文檔的自動實現的屬性裏的代碼就很不錯:ip
// 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訪問器,或者是單純地起個更好的變量名,你老是能夠找到辦法來避免用下劃線_
開頭。文檔