C#ImmutableList和ReadOnlyCollection的区别

时间:2021-06-02 20:35:02   收藏:0   阅读:0
            var intList = new List<int>() { 1 };

            var readOnlyList = new ReadOnlyCollection<int>(intList);
            var immutableList = intList.ToImmutableList();


            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("新增前--------------");
           
            Console.WriteLine("ReadOnlyCollection的数量:" + readOnlyList.Count);
            Console.WriteLine("ImmutableList的数量:" + immutableList.Count);

            intList.Add(2);

            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.WriteLine("新增后--------------");
            
            Console.WriteLine("ReadOnlyCollection的数量:" + readOnlyList.Count);
            Console.WriteLine("ImmutableList的数量:" + immutableList.Count);

技术图片

总结

ReadOnlyCollection只是对原对象的包装。修改原对象还是会影响当前对象。所以不是线程安全的
ImmutableList则是真正不可变的。是线程安全的

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!