zoukankan      html  css  js  c++  java
  • 为什么我不建议在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访问器,或者是单纯地起个更好的变量名,你总是可以找到办法来避免用下划线_开头。

    当然啦,如果你的项目早就已经采用了微软推荐的代码风格,那就要和项目保持一致。

    博客已迁移到 blog.pythonking.top,如果地址失效或者有其他问题请到 github.com/DongchengWang/my-blog
  • 相关阅读:
    JMeter4.0的单机压测和集群压测简介
    接口自动化测试,完整入门篇
    jmeter实战---正则提取器
    压测必经之路,解读JMeter分布式
    JMeter线程组参数含义
    jmeter生成HTML性能测试报告
    SPP-Net、Atrous Convolution以及ASPP by Rose
    使用CNN进行角度估计
    Java相关书籍分享
    Code Conventions for the Java
  • 原文地址:https://www.cnblogs.com/stardust233/p/12375294.html
Copyright © 2011-2022 走看看