readonly关键字是可以在字段上使用的修饰符。当字段声明包括 readonly 修饰符时,该声明引入的字段赋值只能作为声明的一部分出现,或者出现在同一类的构造函数中。
在此示例中,字段 year 的值无法在 ChangeYear 方法中更改,即使在类构造函数中给它赋了值。
1 class Age 2 { 3 readonly int _year; 4 Age(int year) 5 { 6 _year = year; 7 } 8 void ChangeYear() 9 { 10 //_year = 1967; // Compile error if uncommented. 11 } 12 }
public readonly int y = 5;
1 public class ReadOnlyTest 2 { 3 class SampleClass 4 { 5 public int x; 6 // Initialize a readonly field 7 public readonly int y = 25; 8 public readonly int z; 9 10 public SampleClass() 11 { 12 // Initialize a readonly instance field 13 z = 24; 14 } 15 16 public SampleClass(int p1, int p2, int p3) 17 { 18 x = p1; 19 y = p2; 20 z = p3; 21 } 22 } 23 24 static void Main() 25 { 26 SampleClass p1 = new SampleClass(11, 21, 32); // OK 27 Console.WriteLine("p1: x={0}, y={1}, z={2}", p1.x, p1.y, p1.z); 28 SampleClass p2 = new SampleClass(); 29 p2.x = 55; // OK 30 Console.WriteLine("p2: x={0}, y={1}, z={2}", p2.x, p2.y, p2.z); 31 } 32 } 33 /* 34 Output: 35 p1: x=11, y=21, z=32 36 p2: x=55, y=25, z=24 37 */
在前面的示例中,如果使用这样的语句:
p2.y = 66; // Error
将收到编译器错误信息:
The left-hand side of an assignment must be an l-value
这与尝试将值赋给常数时收到的错误相同。
readonly 关键字与 const 关键字不同。const 字段只能在该字段的声明中初始化。readonly 字段可以在声明或构造函数中初始化。因此,根据所使用的构造函数,readonly 字段可能具有不同的值。另外,const 字段为编译时常数,而 readonly 字段可用于运行时常数,如下例所示:
public static readonly uint timeStamp = (uint)DateTime.Now.Ticks;
Reference: http://msdn.microsoft.com/zh-cn/library/acdd6hb7.aspx
Additional:
The modifier readonly means that the value cannot be assigned except in the declaration or constructor. It does not mean that the assigned object becomes immutable(不可变)。
1 public static class MyList 2 { 3 public static readonly SortedList<int, List<myObj>> CharList; 4 // ...etc. 5 }
But even using readonly, you can still add items to the list from another class.
MyList.CharList[100] = new List<myObj>() { new myObj(30, 30) }; //or MyList.CharList.Add(new List<myObj>() { new myObj(30, 30) });
C# readonly const,布布扣,bubuko.com
原文:http://www.cnblogs.com/wxin/p/3596385.html