c# - How add a List of Elements into a list without reference?
问题描述
I cannot find an answer because it seems too much specific. So here's my issue with C#. We can add another list to another one as a clone like this
list2 = new List<int>(list1);
What I want to know is how can I add a List into another one without any reference of the child?
List<List<List<int>>> wireCoords = new List<List<List<int>>>();
List<int> coord = new List<int>();
for(int i = 0; i < inputSplits.Length; i++)
{
coord.Add(0);
coord.Add(0);
wireCoords[i].Add(coord);
}
AS soon the wireCoords[0][0] list change, it also change inside wireCoords[1][0] How can I fix this?
解决方案
Two things. You cannot access a List via [i] accessor unless it has content at that index. Second, you can copy the values of a list by using List1.AddRange(List2). After this, changing List2 will not change List1.
In your for loop, the number of items grow to inputSplits.Length * 2 for every index of wiredCoords. To explain why this happens, lets take an example.
List<int> object1 = new List<int>();
object1.Add(1);
object1.Add(2);
List<int> object2 = object1;
object1.Add(3);
// at this time, object2 also has an element 3.
Console.WriteLine(string.Join(",", object2));
output:
1,2,3 (instead of 1,2 that you'd normally expect)
object1 never gets assigned the "value" of object2. object1 will get "reference" of the object2 and anywhere in code when you change values of object1, object2 will automatically get updated.
Fix for that could be
List<int> object2 = object1;
object1 = new List<int>(); // re-initialized
object1.Add(3);
// object1 has only 1 element
// object2 has 2 elements.
To resolve this, you create a new object or re-initialize the object to get a new reference and then use that for later assignments.
Your code:
List<List<List<int>>> wireCoords = new List<List<List<int>>>();
List<int> coord ;
for(int i = 0; i < inputSplits.Length; i++)
{
coord = new List<int>();
coord.Add(0);
coord.Add(0);
wireCoords.Add(coord);
}
Hope it helps.
推荐阅读
- python - prepopulated_fields 导入数据库时不会触发
- php - 使用 laravel 使用 ajax 调用请求未定义
- javascript - 烧瓶 api 和 javascript 的 CORS 问题
- python - 数据框应用方法未更新所有行
- java - 发现无效的 Gradle JDK 配置。在 Android Studio 中打开 Gradle 设置更改 JDK 位置而 JDK 在任何地方都找不到
- java - 在 Glassfish-Netbeans 中找不到 Java 资源文件
- powershell - 如何以非管理员用户身份运行“Get-CimInstance”(windows server 2019,powershell 5.1)
- javascript - Reactjs-如何将数据或变量从一个组件传递到另一个组件
- accessibility - 使屏幕阅读器可以访问使用 react-virtualized Grid privative 制作的表格
- reactjs - React useMemo:如何全局缓存对象(不是每个钩子使用)