readonly關鍵字用於修飾字段。當字段被聲明為readonly後,則只能在對應類中聲明時和構造函數中對其賦值。
public readonly int y = 5;
class Age
{
readonly int _year;
Age(int year)
{
_year = year;
}
void ChangeYear()
{
//_year = 1967; // Compile error if uncommented.
}
}
字段_year被聲明為readonly,所以在構造函數中為其賦值,在方法ChangeYear中則無法更改。
const字段只能在聲明時初始化,readonly則可以在聲明時和構造函數充初始化。因此,根據構造函數的不同,readonly字段可能具有不同的值。另外,const為編譯時常量,readonly字段可用於運行時常量,如下:
public static readonly uint timeStamp = (uint)DateTime.Now.Ticks;
示例
public class ReadOnlyTest
{
class SampleClass
{
public int x;
// Initialize a readonly field
public readonly int y = 25;
public readonly int z;
public SampleClass()
{
// Initialize a readonly instance field
z = 24;
}
public SampleClass(int p1, int p2, int p3)
{
x = p1;
y = p2;
z = p3;
}
}
static void Main()
{
SampleClass p1 = new SampleClass(11, 21, 32); // OK
Console.WriteLine("p1: x={0}, y={1}, z={2}", p1.x, p1.y, p1.z);
SampleClass p2 = new SampleClass();
p2.x = 55; // OK
Console.WriteLine("p2: x={0}, y={1}, z={2}", p2.x, p2.y, p2.z);
}
}
/*
Output:
p1: x=11, y=21, z=32
p2: x=55, y=25, z=24
*/
可以看到,調用不同構造函數,readonly的值不同。
對上面的例子,如果使用下面的語句:
p2.y = 66; // Error
將收到編譯器錯誤信息:
The left-hand side of an assignment must be an l-value
這與嘗試將值賦給常數時收到的錯誤相同。