http://blog.csdn.net/lltaoyy/article/details/6720778 C#中數(shù)組復制有多種方法 數(shù)組間的復制,int[] pins = {9,3,4,9};int [] alias = pins;這里出了錯誤,也是錯誤的根源,以上代碼并沒有出錯,但是根本不是復制,因為pins和alias都是引用,存在于堆棧中,而數(shù)據(jù)9,3,4,3是一個int對象存在于堆中,int [] alias = pins;只不過是創(chuàng)建另一個引用,alias和pins同時指向{9,3,4,3},當修改其中一個引用的時候,勢必影響另一個。復制的意思是新建一個和被復制對象一樣的對象,在C#語言中應該有如下4種方法來復制。 方法一:使用for循環(huán) int []pins = {9,3,7,2} int []copy = new int[pins.length]; for(int i =0;i!=copy.length;i++) { copy[i] = pins[i]; } 方法二:使用數(shù)組對象中的CopyTo()方法 int []pins = {9,3,7,2} int []copy2 = new int[pins.length]; pins.CopyTo(copy2,0); 方法三:使用Array類的一個靜態(tài)方法Copy() int []pins = {9,3,7,2} int []copy3 = new int[pins.length]; Array.Copy(pins,copy3,copy.Length); 方法四:使用Array類中的一個實例方法Clone(),可以一次調(diào)用,最方便,但是Clone()方法返回的是一個對象,所以要強制轉(zhuǎn)換成恰當?shù)念愵愋汀?/p> int []pins = {9,3,7,2} int []copy4 = (int [])pins.Clone(); 方法五: string[] student1 = { "$", "$", "c", "m", "d", "1", "2", "3", "1", "2", "3" }; string[] student2 = { "0", "1", "2", "3", "4", "5", "6", "6", "1", "8", "16","10","45", "37", "82" }; ArrayList student = new ArrayList(); foreach (string s1 in student1) { student.Add(s1); } foreach (string s2 in student2) { student.Add(s2); } string[] copyAfter = (string[])student.ToArray(typeof(string)); 兩個數(shù)組合并,最后把合并后的結(jié)果賦給copyAfter數(shù)組,這個例子可以靈活變通,很多地方可以用 請選中你要保存的內(nèi)容,粘貼到此文本框 |
|