我有以下代码:
//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数组,并且必须列出它的列表?
发布于 2012-08-09 10:15:17
您希望创建一个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#具有一些功能来创建元素的数组,这些元素都是使用您只指定一次的构造函数初始化的,但这是不可能的。
发布于 2012-08-09 10:10:06
_collectionOfQueues = new BlockingCollection<ConcurrentQueue<T>>[4];
for (int i = 0; i < 4; i++)
_collectionOfQueue[i] = new ConcurrentQueue<T>();发布于 2012-08-09 10:11:14
声明如下:
private BlockingCollection<ConcurrentQueue<T>>[] _collectionOfQueues;初始化如下:
_collectionOfQueues = new BlockingCollection<ConcurrentQueue<T>>[4];
for (int i = 0; i < 4; i++)
_collectionOfQueue[i] = new ConcurrentQueue<T>();https://stackoverflow.com/questions/11881047
复制相似问题