t student)
{
this.Student = student;
}
}
School实例的Student是一个引用类型的变量,赋值后,变量不能再指向其他任何的Student实例,所以,下面的代码将不会编译通过:
School school = new School(new Student(10));
school.Student = new Student(20);//错误信息:无法对只读的字段赋值(构造函数或变量初始化器中除外)
引用本身不可以改变,但是引用说指向的实例的值是可以改变的。所以下面的代码是可以编译通过的:
School school = new School(new Student(10));
school.Student.Age = 20;
在构造方法中,我们可以多次对Readonly修饰的常量赋值。举个例子说明一下:
public class Student
{
public readonly int Age = 20;//注意:初始化器实际上是构造方法的一部分,它其实是一个语法糖
public Student(int age)
{
this.Age = age;
this.Age = 25;
this.Age = 30;
}
}
总结
Const和Readonly的最大区别(除语法外)
Const的变量是嵌入在IL代码中,编译时就加载好,不依赖外部dll(这也是为什么不能在构造方法中赋值)。Const在程序集更新时容易产生版本不一致的情况。
Readonly的变量是在运行时加载,需请求加载dll,每次都获取最新的值。Readonly赋值引用类型以后,引用本身不可以改变,但是引用所指向的实例的值是可以改变的。在构造方法中,我们可以多次对Readonly赋值。