{C#}private字段的命名风格

2022-07-23  本文已影响0人  码农猫爸
问题
结论
演示代码
using System;

// 私有字段命名
namespace _001_PrivateFieldNaming
{
    // 常规方式
    class Normal
    {
        // 根据C#命名规则
        // - private字段,必须遵循camel方式
        // - protected字段,可根据个人喜好任选camel或Pascal方式
        private readonly int x;
        protected readonly int Y;

        public int Z { get; set; }

        public Normal(int x, int y)
        {
            this.x = x;
            Y = y;
        }

        public void Method(int x) => Console.WriteLine(this.x > x);
    }

    // 建议方式
    class Suggestion
    {
        // 差异1:
        // - private字段命名,首字母采用下划线
        // - protected字段套用此方式后,与属性自然区分
        private readonly int _x;
        protected readonly int _y;

        public int Z { get; set; }

        // 差异2:
        // - 构造器中,自然区分字段与参数,无需this
        public Suggestion(int x, int y)
        {
            _x = x;
            _y = y;
        }

        // 差异3:
        // - 方法中,自然区分字段与参数,无需this
        public void Method(int x) => Console.WriteLine(_x > x);
    }
}

上一篇 下一篇

猜你喜欢

热点阅读