首先,我们看一下下面一段代码,每个Color实例都有自己独立的R,G,B实例变量,但是只有一份Black,White,Red,Green,Blue静态字段:
public class Color
{
public static readonly Color Black = new Color(0, 0, 0);
public static readonly Color White = new Color(255, 255, 255);
public static readonly Color Red = new Color(255, 0, 0);
public static readonly Color Green = new Color(0, 255, 0);
public static readonly Color Blue = new Color(0, 0, 255);
private byte r, g, b;
public Color(byte r, byte g, byte b)
{
this.r = r;
this.g = g;
this.b = b;
}
}
上面的readonly修饰符,表示那些变量是只读字段, 只有在变量声明阶段或者在这个类的构造函数里才允许对readonly的变量进行赋值。
readonly保护的是变量的位置(而非那个位置上的