初始化引用类型对象数组的简洁方法 [英] The concise way to initialize an array of reference type object

查看:67
本文介绍了初始化引用类型对象数组的简洁方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有更好的方法来初始化引用类型对象的数组,像这样.

I wonder if there is better way to initialize an array of reference type object, like this.

Queue<int>[] queues = new Queue<int>[10];
for (int i = 0; i < queues.Length; i++)
    queues[i] = new Queue<int>();

我尝试了Enumerable.Repeat,但是数组中的所有元素都引用相同的实例,

I tried Enumerable.Repeat, but all elements in the array refer to same instance,

Queue<int>[] queues = Enumerable.Repeat(new Queue<int>(), 10).ToArray();

我也尝试了Array.ForEach,但是如果没有ref关键字,它将无法正常工作

I also tried Array.ForEach, but it doesn't work without ref keyword:

Queue<int>[] queues = Array.ForEach(queues, queue => queue = new Queue<int>());

还有其他想法吗?

推荐答案

您可以使用:

Enumerable.Range(0,10).Select(_=>new Queue<int>()).ToArray()

但是IMO,您的第一个例子也很好.

But IMO your first example is perfectly fine too.

这篇关于初始化引用类型对象数组的简洁方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆