gpt4 book ai didi

C# List AddRange - 它是否复制通过引用添加的项目

转载 作者:太空宇宙 更新时间:2023-11-03 15:09:05 43 4
gpt4 key购买 nike

比如说,我有 3 个列表

List<int> l1
List<int> l1,l2,l3

所有 3 个列表都有很多项目我想将它们全部添加到一个列表中

List<int> finalList
finalList.AddRange(l1) , similarly for l2 and l3.

在执行 finalList.AddRange 时,它是从 l1、l2、l3 复制项目还是仅引用这些项目?如果它复制我想避免 AddRange 以节省内存,因为列表很大。

最佳答案

如果您希望复制引用而不是数据,请将您的整数列表包装到如下类中:

    public class ItemsList
{
public List<int> ListOfInts {get; set;}

public ItemsList()
{
ListOfInts = new List<int>();
}
}

然后像下面这样添加它们:

        ItemsList l1 = new ItemsList();
l1.ListOfInts = new List<int> { 1, 2, 3, 4, 5, 6 };//or whatever data inside

//same for l2, l3

List<ItemsList> finalList = new List<ItemsList>();
finalList.Add(l1);//Your adding references to ItemsList class

希望这有用。

关于C# List AddRange - 它是否复制通过引用添加的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41992621/

43 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com