我正在使用一个 ImmutableList,如下所示:
使用Nuget引用包,下面是使用代码:
using System.Collections.Immutable; private ImmutableList<Data> immutableList = ImmutableList.Create<Data>(); // Write Action Action writeAction = (() => { Data writeData = new Data(); // Fill Data type with valid values immutableList.Add(writeData); });
上面的代码没有向不可变列表添加任何数据。它仍然是空的,当所有数据都有效时我无法弄清楚原因。类似的代码用于填充其他数据结构,如 ConcurrentQueue 和 ConcurrentBag,并且工作正常。
我是否遗漏了不可变列表的用法,是否需要更正? 请注意,这是一个多线程操作,但这不是问题,因为此数据结构是线程安全的。
最佳答案
顾名思义列表是不可变的,即您不能将项目添加到原始列表中。在 MSDN 链接的备注部分:
When you add or remove items from an immutable list copy of the original list is made with the items added or removed, and the original list is unchanged.
同样来自 here 的 Add 方法文档:
It returns a new immutable list with the object added, or the current list if it already contains the specified object.
添加将为您提供新的列表引用,其中添加了项目(原始列表将保持不变):
immutableList = immutableList.Add(writeData);
关于c# - 不可变列表不添加数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25824158/