2010-07-18 22 views
0

1)const int[] array={1,2,3,4}; //this gives below error引用類型常數初始化和Array concetanation

"Error 1 'ConsoleApplication1.Main.array' is of type 'int[]'. 
A const field of a reference type other than string can only be initialized with null" 

在根據錯誤messeagge我看來,這是不meaningfull用於參考types.Am我錯常量?

2)如何連接int數組?例如:

int[] x={1,2,3} + {4,5,6}; 

我知道+運算符將無法正常工作,所以將它作爲字符串的最佳方式是什麼?

回答

2

Concat擴展方法做到這一點。不是很清晰的代碼,但是。

(new int[] { 1, 2, 3, 4 }).Concat(new int[] { 5, 6, 7, 8 }).ToArray(); 
2

1)是的,唯一有用的參考類型是String。

2)要連接陣列創建一個新的數組和複製的數組的內容吧:

int[] a = { 1, 2, 3 }; 
int[] b = { 4, 5, 6 }; 

int[] x = new int[a.Length + b.Length]; 
a.CopyTo(x, 0); 
b.CopyTo(x, a.Length); 

我不知道你算什麼是「最好」的方法,但這是最有效率。 (一個快速測試表明,這比使用Concat擴展方法快10-20倍。)

+0

我沒有說過性能點。我只是對可讀性和清晰度更感興趣。 – Freshblood 2010-07-19 12:45:39