变量命名
1、static readonly与const的变量
作用是一样的,无论访问修饰符是不是public,还是其它(private、 protected、internal),变量名称一般为大写,中间以下划线。
public static readonly int MAX_HEIGHT;
public const int MIN_HEIGHT = 10;
public const int MIN_HEIGHT = 10;
有些程序员对大写不敏感,上例中,MAX_HEIGHT用Max_Height代替也未尝不可 ,甚至MaxHeight也可以。在.Net类库中,int.MaxValue与int.MinValue便是这样定义的。
const常量更确切的说是编译时常量,因为它在运行时是不存在的,在编译中所有变量引用将被实际值替掉。而 static readonly则不然,它在运行时也是存在的。从原理上讲,论效率const优于static readonly。但是在一个比较在的项目中, 在dll局部升级时,如果改变了某个const变量的值,而未升级的dll如果也有这个const变量的话,显而易见这时候问题将是产生。如 果因此而升级全部dll,反而不值。所以在大型、多变应用中,建议使用static readonly代替const。其微乎其微的效率的减损对比 升级布置可能出现的问题还是可以接受的。
2、除了以上两种静态只读和常量变量之外,其它变量命名均以下划线开始
访问修改符为private(不建议命名为 internal、protected,更不建议命名为public):
private static int _maxHeight;
private int _minHeight;
private int _minHeight;
作用: 如果其命名不前置下划线,易与参数变量混淆。
对于下面这种定义:
private int _minHeight = default(int);
public int MinHeight
{
set{
_minHeight = value;
}
get{
return _minHeight;
}
}
public int MinHeight
{
set{
_minHeight = value;
}
get{
return _minHeight;
}
}