标签:javascrip 语言 tom ase obj customer 官方 混淆 methods
我经常在一些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。这样做会有什么问题呢?
_重复表示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访问器,或者是单纯地起个更好的变量名,你总是可以找到办法来避免用下划线_开头。
标签:javascrip 语言 tom ase obj customer 官方 混淆 methods
原文地址:https://www.cnblogs.com/stardust233/p/12375294.html