我在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#本身已經(jīng)提供了private修飾符艾栋,不需要再用下劃線
_
重復(fù)表示private - 下劃線
_
已經(jīng)用來表示棄元的功能了爆存,是不是會造成混淆呢?
實際上我簡單地使用駝峰命名法蝗砾,不用下劃線_
開頭先较,也不會有什么問題。代碼如下:
public class Date
{
private int month = 7; // Backing store
public int Month
{
get => month;
set
{
if ((value > 0) && (value < 13))
{
month = value;
}
}
}
}
這樣看起來更簡潔悼粮,更容易理解了闲勺。下面同樣來自官方文檔的自動實現(xiàn)的屬性里的代碼就很不錯:
// 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訪問器菜循,或者是單純地起個更好的變量名,你總是可以找到辦法來避免用下劃線_
開頭申尤。
當(dāng)然啦癌幕,如果你的項目早就已經(jīng)采用了微軟推薦的代碼風(fēng)格,那就要和項目保持一致昧穿。