码迷,mamicode.com
首页 > Windows程序 > 详细

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

时间:2020-02-28 01:24:41      阅读:176      评论:0      收藏:0      [点我收藏+]

标签: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。这样做会有什么问题呢?

  • 项目混合使用了驼峰命名法与下划线命名法,扰乱了阅读代码的视线
  • 不像其他语言(比如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访问器,或者是单纯地起个更好的变量名,你总是可以找到办法来避免用下划线_开头。

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

标签:javascrip   语言   tom   ase   obj   customer   官方   混淆   methods   

原文地址:https://www.cnblogs.com/stardust233/p/12375294.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!