c#学习笔记-------------------------readonly修饰符

发布时间 2023-12-19 11:29:09作者: 我们打工人

一、ReadOnly关键字

MSDN 官方的解释

readonly 关键字是可以在字段上使用的修饰符。当字段声明包括 readonly 修饰符时,该声明引入的字段赋值只能作为声明的一部分出现,或者出现在同一类的构造函数中.
具体意思是:
  1. readonly是一个修饰字段的关键字:被它修饰的字段只有在初始化或者构造函数中才能够赋值.
  2. readonly修饰的引用类型字段必须始终引用同一对象: readonly 修饰符可防止字段替换为引用类型的其他实例, 但是,readonly不会妨碍通过该字段修改字段引用的数据。
  private readonly  List<int> _testInt;
    Program( List<int> testInt) 
    {
        _testInt = testInt;
    }
    static void Main(string[] args)
    {
        ChangeReadonlyRef();
    }
 
    static void ChangeReadonlyRef() 
    {
        var l = new  List<int>{1};
        var program = new Program(l);
        Console.WriteLine($"testInt.Count= {program._testInt.Count()}");
        l = new List<int>();   // l 变量重新指向。 但是 _testInt 还是指向原来的引用。
        Console.WriteLine($"testInt.Count= {program._testInt.Count()}");
        program._testInt = new List<int>();  //编译报错!!
    }