• 博客园logo
  • 会员
  • 周边
  • 众包
  • 新闻
  • 博问
  • 闪存
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
学习笔记
Misaka的学习笔记
博客园    首页    新随笔    联系   管理    订阅  订阅
c#学习笔记-------------------------readonly修饰符

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

 

posted on 2023-12-19 11:26  我们打工人  阅读(271)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3