特点
- 属运行时常量,占内存
- 定义时或构造器中赋值,仅修饰字段
- 引用类型时,其子字段可改值,即其地址只读。
- 归创建它的实例独有,共有时加前缀static
- 支持所有数据类型
using System.Collections.Generic;
using static System.Console;
namespace ReadOnlyDemo
{
class Program
{
static void Main(string[] args)
{
var demo = new Demo();
demo.Reset();
ReadKey();
}
}
public class Demo
{
// 值类型,声明时赋值OK
private readonly string name = "zhang";
private readonly int age;
// 引用类型,声明时赋值OK
private readonly List<Person> persons = new List<Person>
{
new Person("张三",10),
new Person("李四",20),
};
// 构造器内赋值OK
public Demo()
{
name = "li";
age = 15;
persons = new List<Person>
{
new Person("王五",30),
new Person("曹六",40),
};
}
public void Reset()
{
// 只读值类型,报错情形
// name = "曹六";
// age = 15;
// 只读引用类型,许可情形
persons[0] = new Person("曹六", 25);
persons[0].Name = "曹六一";
persons[0].Age = 35;
// 只读引用类型,报错情形
// persons = null;
}
}
public class Person
{
public string Name;
public int Age;
public Person(string name, int age)
{
Name = name;
Age = age;
}
}
}
网友评论