问题
- C#命名风格中,private字段开头按有无下划线可分为2派,其中大咖以偏爱下划线居多
结论
- 下划线优势:
- 自然区分字段和参数,或字段和属性
- 可省略this限定符
- 建议扩展到protected字段
演示代码
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);
}
}
网友评论