You can assign a value to a readonly field only in the following contexts:
When the variable is initialized in the declaration
public readonly int y = 5;
In an instance constructor of the class that contains the instance field declaration.
In the static constructor of the class that contains the static field declaration.
A readonly field can’t be assigned after the constructor exits. This rule has different implications for value types and reference types:
Because value types directly contain their data, a field that is a readonly value type is immutable.
Because reference types contain a reference to their data, a field that is a readonly reference type must always refer to the same object. That object isn’t immutable. The readonly modifier prevents the field from being replaced by a different instance of the reference type. However, the modifier doesn’t prevent the instance data of the field from being modified through the read-only field.
run-time constants
样例
public class SamplePoint
{
public int x;
// Initialize a readonly field
public readonly int y = 25;
public readonly int z;
public SamplePoint()
{
// Initialize a readonly instance field
z = 24;
}
public SamplePoint(int p1, int p2, int p3)
{
x = p1;
y = p2;
z = p3;
}
public static void Main()
{
SamplePoint p1 = new SamplePoint(11, 21, 32); // OK
Console.WriteLine($"p1: x={p1.x}, y={p1.y}, z={p1.z}");
SamplePoint p2 = new SamplePoint();
p2.x = 55; // OK
Console.WriteLine($"p2: x={p2.x}, y={p2.y}, z={p2.z}");
}
/*
Output:
p1: x=11, y=21, z=32
p2: x=55, y=25, z=24
*/
}