readonly与const的区别,要使用const的理由是效率高。
(1)、const是编译常量,readonly是运行常量
(2)、const是修饰基础类型,readonly没有限制
public const int Cvalue = 100;
public const static int Cvalue = 100; // 编译异常
readonly是运行是常量,第一次复制后不可改变。
"不可改变"分两层含义。
(1)、值类型变量,值本身是不可能改变的(readonly,只读)
(2)、引用类型变量,引用类型本身不可改变,字段
public class ReadOnlyInstance
{
public ReadOnlyInstance(int id ) {
this.ID = id;
worker = new Worker();
}
public readonly int ID;
public readonly Worker worker;
}
public class Worker
{
public string Name { get; set; } = "nickname";
public int Age { get; set; } = 30;
public override string ToString()
{
return "Name:" + Name + "age:" + Age;
}
}
测试:
ReadOnlyInstance roi = new ReadOnlyInstance(13);
// roi.worker = new Worker(); 异常
Console.WriteLine("默认值");
Console.WriteLine(roi.worker.ToString());
roi.worker.Age = 20;
// 修改值
Console.WriteLine("修改值");
Console.WriteLine(roi.worker.ToString());
结果:
标签:roi,const,区别,int,worker,readonly,public From: https://www.cnblogs.com/panpeng666/p/17626387.html