readonly關(guān)鍵字用于修飾字段。當(dāng)字段被聲明為readonly后,則只能在對應(yīng)類中聲明時和構(gòu)造函數(shù)中對其賦值。
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,所以在構(gòu)造函數(shù)中為其賦值,在方法ChangeYear中則無法更改。
const字段只能在聲明時初始化,readonly則可以在聲明時和構(gòu)造函數(shù)充初始化。因此,根據(jù)構(gòu)造函數(shù)的不同,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 */
可以看到,調(diào)用不同構(gòu)造函數(shù),readonly的值不同。
對上面的例子,如果使用下面的語句:
p2.y = 66; // Error
將收到編譯器錯誤信息:
The left-hand side of an assignment must be an l-value
這與嘗試將值賦給常數(shù)時收到的錯誤相同。
新聞熱點
疑難解答