C# readonly修饰符

发布时间 2023-08-18 18:24:47作者: 博客猿马甲哥

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>();  //编译报错!!
    }