首页 > 解决方案 > 为什么将列表转换为数组而不是在 c# 中引用?

问题描述

.Net 中的数组是引用类型。给定上面的两个代码段。问题:为什么设置值变量“fixedItem”影响第一段代码中的变量“数据”,但第二段代码不影响

第一个代码段:

        var data = new List<IList<int>>();
        data.Add(new List<int>() { 1, 2, 3 });
        data.Add(new List<int>() { 3, 8, 6,5 });
        data.Add(new List<int>() { 1, 2 });
        var fixedItem = data.Last();
        fixedItem[1] = 8;
        
        //Result:
        //data = {{1,2,3}, {3,8,6,5}, {1,8}}

第二段代码:

        var data = new List<IList<int>>();
        data.Add(new List<int>() { 1, 2, 3 });
        data.Add(new List<int>() { 3, 8, 6,5 });
        data.Add(new List<int>() { 1, 2 });
        var fixedItem = data.Last().ToArray();
        fixedItem[1] = 8;
          
        //Result:
        //data = {{1,2,3}, {3,8,6,5}, {1,2}}

标签: c#arrayslist

解决方案


文档

根据文档 list.ToArray() 方法返回带有原始列表副本的数组


推荐阅读