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

我常常在一些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

  • 项目混合使用了驼峰命名法与下划线命名法,扰乱了阅读代码的视线
  • 不像其余语言(好比JavaScript),C#自己已经提供了private修饰符,不须要再用下划线_重复表示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访问器,或者是单纯地起个更好的变量名,你老是能够找到办法来避免用下划线_开头。文档

相关文章
相关标签/搜索