c# - 不可变列表不添加数据

标签 c# .net multithreading

我正在使用一个 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/

相关文章:

c# - 在哪里将实体/模型转换为 MVVM 中的 View 模型?

c# - 调整窗口大小 C#

c# - 在 FxCop 自定义规则中使用 SerializationAttribute 检测类

c# - 必须将单个字符串传递给多个正则表达式模式,并且在匹配时我想要匹配的值

c# - 重构 PropertyChangedEventHandler

multithreading - Go语言中线程的同步

windows - VB - 以隐式方式链接 DLL

c# - JWT 承载身份验证不从 header 读取 token

java - 处理 2 - 线程会加速渲染许多对象吗?

c# - 如何创建有意义的动态属性?