2

我有以下代码:

//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我必须列出它吗?

4

4 回答 4

2
_collectionOfQueues = new BlockingCollection<ConcurrentQueue<T>>[4];
for (int i = 0; i < 4; i++)
    _collectionOfQueue[i] = new ConcurrentQueue<T>();
于 2012-08-09T10:10:06.070 回答
2

声明如下:

private BlockingCollection<ConcurrentQueue<T>>[] _collectionOfQueues;

初始化如下:

_collectionOfQueues = new BlockingCollection<ConcurrentQueue<T>>[4];
for (int i = 0; i < 4; i++)
    _collectionOfQueue[i] = new ConcurrentQueue<T>();
于 2012-08-09T10:11:14.447 回答
1

这与阻塞集合无关。您用于创建特定大小的数组并初始化其成员的语法无效。

尝试:

_collectionOfQueues = Enumerable.Range(0, 4)
                                .Select(index => new BlockingCollection<T>())
                                .ToArray();

顺便说一句,您不必显式创建一个ConcurrentQueue<T>类似的(只需使用默认构造函数),因为这是 a 的默认支持集合BlockingCollection<T>

于 2012-08-09T10:10:27.663 回答
1

你想创建一个四元素的BlockingCollection<T>实例数组,并且你想用一个接受实例的构造函数来初始化每个ConcurrentQueue<T>实例。(请注意,默认构造函数 forBlockingCollection<T>将使用 aConcurrentQueue<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# 具有一些功能来创建数组,其中所有元素都使用您只指定一次的相同构造函数进行初始化,但这是不可能的。

于 2012-08-09T10:15:17.397 回答