google到一篇讲const 与 static readonly的文章 还不错~草译一下
The difference is that the value of a static readonly field is set at run time, and can thus be modified by the containing class, whereas the value of a const field is set to a compile time constant.
被 static readonly修饰的字段 是在运行时中被设置值,可以修改. const 修饰的字段是在编译时被设置值。
(const 修饰的字段的值直接被写进IL中间码里面)
In the static readonly case, the containing class is allowed to modify it only
只有 static readonly 字段的包含类才可以对其进修赋值修改
in the variable declaration (through a variable initializer)
in the static constructor (instance constructors, if it's not static)
static readonly is typically used if the type of the field is not allowed in a const declaration, or when the value is not known at compile time.
Instance readonly fields are also allowed.
Remember that for reference types, in both cases (static and instance) the readonly modifier only prevents you from assigning a new reference to the field. It specifically does not make immutable the object pointed to by the reference.
class Program
{
public static readonly Test test = new Test();
static void Main(string[] args)
{
test.Name = "Program";
test = new Test(); // Error: A static readonly field cannot be assigned to (except in a static constructor or a variable initializer)
}
}
class Test
{
public string Name;
}
On the other hand, if Test were a value type, then assignment to test.Name would be an error.