如果需要一个具有常数值的符号名称,但该值的类型不允许在 const 声明中使用,或者无法在编译时计算出该值,则 static readonly 字段就可以发挥作用了。在下面的示例中
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);
{
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 red, green, blue;
public Color(byte r, byte g, byte b) {
red = r;
green = g;
blue = b;
}
}
Black、
White、
Red、
Green 和
Blue 成员不能被声明为
const 成员,这是因为在编译时无法计算它们的值。不过,将它们声明为
static readonly 能达到基本相同的效果。
red = r;
green = g;
blue = b;
}
}
常量和只读字段具有不同的二进制版本控制语义。当表达式引用常量时
,
该常量的值在编译时获取
,
但是当表达式引用只读字段时
,
要等到运行时才获取该字段的值。请考虑一个包含两个单独程序的应用程序:
using System;
namespace Program1
{
public class Utils
{
public static readonly int X = 1;
}
}
{
public class Utils
{
public static readonly int X = 1;
}
}
namespace Program2
{
class Test
{
static void Main() {
Console.WriteLine(Program1.Utils.X);
}
}
}
{
class Test
{
static void Main() {
Console.WriteLine(Program1.Utils.X);
}
}
}