1.封装数据
除了属性和访问修饰符,还可以用const和readonly。
1.1const
称为常量字段,不可以在运行时改变,比如圆周率这种值就很适合声明为常量字段。常量字段自动成为静态字段,但是将常量字段显示声明为static的时候会造成编译错误。
常量字段只使用包含字面量的类型(比如string,int,double等)
public const int c=16;
注意:要为永远不会发生改变的值使用常量字段。
1.2readonly
不同于const,readonly只能用于字段,不能用于局部变量。它可以在构造器中进行修改,既可以是实例化字段,也可以是静态字段。
而且可以使用非包含字面量的类型,eg:public static readonly Guid c=new Guid("00000000000-0-0000000-000023");,const只能使用字面量的类型。
比如:public readonly int _id;
public int id{get{return _id;}}