2012-08-09 76 views
2

我有以下代码:无法创建BlockingCollection阵列

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

我得到以下错误为底线:

无法应用用[]索引,以类型的表达式“系统.Collection.Concurrent.BlockingCollection”

即使我做的:

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

我得到的最后一个方括号的错误:

语法错误;值预期

我试图使BlockingCollection阵列与ConcurrentQueue集合,这样我可以这样做:

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

我在做什么错了,我能做些什么来解决这个问题?我能不能创建一个BlockingCollection的数组,我必须列出它吗?

+0

您不能使用'new'来创建一个数组并像这样填充它。但您可以使用表达式从字面集合中初始化一个数组:'_collectionOfQueues = new BlockingCollection [] {new ConcurrentQueue (),null,null,null};'(添加'null's给它的大小4)。 – Richard 2012-08-09 10:15:33

回答

1

你想创建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#有一些功能来创建数组,其元素都是使用相同的构造函数初始化的,而你只能指定一次,但这是不可能的。

+0

感谢您的回答。 – 3aw5TZetdf 2012-08-09 10:19:19

2
_collectionOfQueues = new BlockingCollection<ConcurrentQueue<T>>[4]; 
for (int i = 0; i < 4; i++) 
    _collectionOfQueue[i] = new ConcurrentQueue<T>(); 
+0

我是否需要单独初始化每个队列才能正常工作? – 3aw5TZetdf 2012-08-09 10:13:01

+0

是的,你必须.. – 2012-08-09 10:13:28

1

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

尝试:

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

顺便说一句,你不必明确创建一个ConcurrentQueue<T>这样(只使用默认的构造函数),因为这是一个BlockingCollection<T>的默认后盾集合。

2

声明如下:

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

初始化如下:

_collectionOfQueues = new BlockingCollection<ConcurrentQueue<T>>[4]; 
for (int i = 0; i < 4; i++) 
    _collectionOfQueue[i] = new ConcurrentQueue<T>(); 
+0

谢谢,它的工作原理!我会尽我所能接受这个答案。 – 3aw5TZetdf 2012-08-09 10:12:26