readonly 关键字的用法

readonly 关键字的用法

readonly 修饰符时,该声明引入的字段赋值只能作为声明的一部分出现,或者出现在同一类的构造函数中。

示例

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.     }
  13.  
  14.  

readonly 字段进行赋值:

  • 当在声明中初始化变量时,例如:

    public readonly int y = 5;
  • readonly字段作为 out 或 ref 参数传递才有效。

readonly 关键字的用法说明

readonly 字段可用于运行时常数,如下例所示:

public static readonly uint timeStamp = (uint)DateTime.Now.Ticks;
  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(112132);   // 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.     */
  38.  
  39.  

在前面的示例中,如果使用这样的语句:

p2.y = 66; // Error

将收到编译器错误信息:

The left-hand side of an assignment must be an l-value

这与尝试将值赋给常数时收到的错误相同。