我想复制一个集合并将新元素添加到其中一个(而不是两个)。
在下面的代码示例中,我通过创建一个新 并将其传递给构造函数来复制集合。之后,我只在其中一个集合中添加了一个元素。之后两个集合都包含新元素...
var listOne = new Collection<Test>();
listOne.Add(new Test());
listOne.Add(new Test());
var listTwo = new Collection<Test>(listOne);
listOne.Add(new Test());
Console.WriteLine(listOne.Count); // 3
Console.WriteLine(listTwo.Count); // 3 (NOT OK)
当我使用列表而不是集合时,它按预期工作。
var listOne = new List<Test>();
listOne.Add(new Test());
listOne.Add(new Test());
var listTwo = new List<Test>(listOne);
listOne.Add(new Test());
Console.WriteLine(listOne.Count); // 3
Console.WriteLine(listTwo.Count); // 2 (OK)
在这两种情况下,我都希望第二个列表只包含 2 个元素。为什么集合和列表之间存在差异?
最佳答案
因为 Collection<T>
和 List<T>
在他们的构造函数中做不同的事情
Initializes a new instance of the Collection class as a wrapper for the specified list.
Initializes a new instance of the List class that contains elements copied from the specified collection [...]
关于c# - 为什么在复制时我的 Collection<T> 与 List<T> 类的工作方式不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57921483/