2012-09-07 58 views
4

我想知道是否有更好的方法來初始化引用類型對象數組,如下所示。初始化引用類型對象數組的簡潔方式

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

我試過Enumerable.Repeat,但陣列中的所有元素是指相同的實例,

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

我也試過Array.ForEach,但它並沒有ref關鍵字工作:

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

任何其他的想法?

+4

我個人認爲,你的第一個例子是完全可以接受的。 –

+1

同意。循環出了什麼問題? –

+0

我知道我的第一個例子非常好,只是好奇,如果有另一種選擇。 – lidong

回答

6

您可以使用此:

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

但IMO你的第一個例子是完全沒有問題了。

4

不,沒有。剛因素它變成一個工具方法:

// CommonExtensions.cs 
public static T[] NewArray<T> (int length) where T : class, new() 
{ 
    var result = new T[length] ; 
    for (int i = 0 ; i < result.Length ; ++i) 
     result[i] = new T() ; 
    return result ; 
} 

// elsewhere 
var queues = Extensions.NewArray<Queue<int>> (10) ; 
+0

@ L.B - 看起來它會返回一組隊列 hatchet

+0

@hatchet是,這正是問題所要求的。 –

+0

由這種專門的幫助函數的IMO膨脹通常是不值得的。 – CodesInChaos

0

我有同樣的答案 - 使用循環。但是,你可以把它作爲通用的擴展方法:

public static void Init<T>(this IList<T> array) 
    { 
     if (array == null) return; 

     for (int i = 0; i < array.Count; i++) 
      array[i] = Activator.CreateInstance<T>(); 
    } 

和叫它:

 Queue<int>[] queues = new Queue<int>[10]; 
     queues.Init();