為什么我不建議在C#中用下划線_開頭來表示私有字段


我在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訪問器,或者是單純地起個更好的變量名,你總是可以找到辦法來避免用下划線_開頭。

當然啦,如果你的項目早就已經采用了微軟推薦的代碼風格,那就要和項目保持一致。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM