readonly C#

readonly 关键字与 const 关键字不同。 const 字段只能在该字段的声明中初始化。 readonly 字段可以在声明或构造函数中初始化 因此,根据所使用的构造函数,readonly 字段可能具有不同的值。 另外,const 字段为编译时常数,而 readonly 字段可用于运行时常数,如下例所示:

 

    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
    */

 

posted @ 2013-05-17 17:43  蓝晓  阅读(143)  评论(0编辑  收藏  举报