无法创建BlockingCollection数组 - c#

我有以下代码:

//In a Class:
private BlockingCollection<T>[] _collectionOfQueues;
// In the Constructor:
_collectionOfQueues = new BlockingCollection<T>(new ConcurrentQueue<T>())[4];

我得到以下错误的底线:

无法将带有[]的索引应用于类型为'System.Collection.Concurrent.BlockingCollection'的表达式

即使我这样做:

_collectionOfQueues = new BlockingCollection<T>(new ConcurrentQueue<T>())[];

我在最后一个方括号上遇到错误:

语法错误;期望值

我正在尝试使用BlockingCollection的集合制作一个ConcurrentQueue数组,以便可以执行以下操作:

_collectionOfQueues[1].Add(...);
// Add an item to the second queue

我在做错什么,我该怎么办才能解决?我不能创建BlockingCollection的数组,我必须列出它吗?

参考方案

您要创建一个由BlockingCollection<T>实例组成的四元素数组,并希望使用接受ConcurrentQueue<T>实例的构造函数初始化每个实例。 (请注意,BlockingCollection<T>的默认构造函数将使用ConcurrentQueue<T>作为后备集合,因此您可以改用默认构造函数,但为演示起见,我将坚持该问题的构造。)

您可以使用集合初始化程序来执行此操作:

BlockingCollection<T>[] _collectionOfQueues = new[] {
  new BlockingCollection<T>(new ConcurrentQueue<T>()),
  new BlockingCollection<T>(new ConcurrentQueue<T>()),
  new BlockingCollection<T>(new ConcurrentQueue<T>()),
  new BlockingCollection<T>(new ConcurrentQueue<T>())
};

或者您可以使用某种循环来实现。使用LINQ可能是最简单的方法:

BlockingCollection<T>[] _collectionOfQueues = Enumerable.Range(0, 4)
  .Select(_ => new BlockingCollection<T>(new ConcurrentQueue<T>()))
  .ToArray();

请注意,您需要以某种方式提供代码以初始化数组中的每个元素。看来您的问题是,您希望C#具有某些功能来创建所有元素都使用仅指定一次的同一构造函数初始化的数组,但这是不可能的。

将谓词<T>转换为Func <T,bool> - c#

我有一个包含成员Predicate的类,希望在Linq表达式中使用该类:using System.Linq; class MyClass { public bool DoAllHaveSomeProperty() { return m_instrumentList.All(m_filterExpression); } private IEnumerable&…

客户端反序列化为数组序列化字典<string,string>数据 - c#

我有一个字典,该字典使用C#中的JavaScriptSerializer进行了序列化。在客户端,我有:"{"dd049eda-e289-4ca2-8841-4908f94d5b65":"2","ab969ac2-320e-42e1-b759-038eb7f57178":"5�…

根据激活的Maven配置文件更新战争名称 - java

在pom中,我有两个配置文件。测试1测试2现在,我希望根据激活的配置文件更改战争名称。预期结果激活test1配置文件后,战争名称应为prefix-test1.war。激活test1和test2时,战争名称应为prefix-test1-test2.war。如果没有激活任何配置文件,则战争名称应为prefix.war。我的POM文件....<?xml ve…

为什么要使用Func <string>而不是string? - c#

为什么要使用Func<string>而不是string?我的问题特别是关于this回购。有问题的行是22: private static Func<string> getToken = () => Environment.GetEnvironmentVariable("GitHubToken", Enviro…

构造函数中的Func <T>参数是否会减慢我的IoC解析速度? - c#

我正在尝试提高IoC容器的性能。我们正在使用Unity和SimpleInjector,并且有一个带有此构造函数的类:public AuditFacade( IIocContainer container, Func<IAuditManager> auditManagerFactory, Func<ValidatorFactory> v…