FROM P105
字段可以用readonly修饰符声明。其作用类似于将字段声明为const,一旦值被设定就不能改变。
--const字段只能在字段的声明语句中初始化,而readonly字段可以在下列任意位置设置它的值:
□字段声明语句,类似const
□类的任何构造函数,如果是static字段,初始化必须在静态构造函数中完成(在并没有在字段声明语句中赋值的情况下)。
--const字段的值必须在编译时决定,而readonly字段的值可以在运行时决定。这种增加的自由性允许你在不同的环境or构造函数中设置不同的值。
--和const不同,const的行为总是静态的,而对于readonly字段以下两点是正确的:
□它可以是实例字段,也可以是静态字段
□它在内存中有存储位置
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace review 8 { 9 class class1 10 { 11 //public const int z; error! const修饰的必须在声明时赋初值 12 //public const int z1 = 5; ok! 13 public readonly int z; 14 //public static readonly int t=5; // ok! 15 public static readonly int T; 16 static class1() 17 { 18 //对于静态 readonly 字段 若声明时未赋值却想使用,就必须在这样的静态构造函数中赋值 19 } 20 public class1() 21 { 22 z = 1; 23 } 24 public class1(int t) 25 { 26 z = 2; 27 } 28 } 29 class Program 30 { 31 static void Main(string[] args) 32 { 33 //class1.T = 5; //无法对静态只读字段赋值(静态构造函数或变量初始值中除外) 34 class1 a1 = new class1(); 35 class1 a2 = new class1(2); 36 Console.WriteLine(a1.z.ToString()); 37 Console.WriteLine(a2.z.ToString()); 38 Console.Read(); 39 } 40 } 41 }
输出:
1
2