C#數(shù)組復(fù)制方法詳解
C#數(shù)組復(fù)制方法有哪些呢?在實際開發(fā)的過程中,我們需要掌握學習的有哪些呢?這里向你介紹5種方法,那么具體的實施方法是什么呢?讓我們看看具體的內(nèi)容。
數(shù)組間的復(fù)制,int[] pins = {9,3,4,9};int [] alias = pins;這里出了錯誤,也是錯誤的根源,以上代碼并沒有出錯,但是根本不是復(fù)制,因為pins和alias都是引用,存在于堆棧中,而數(shù)據(jù)9,3,4,3是一個int對象存在于堆中,int [] alias = pins;只不過是創(chuàng)建另一個引用,alias和pins同時指向{9,3,4,3},當修改其中一個引用的時候,勢必影響另一個。復(fù)制的意思是新建一個和被復(fù)制對象一樣的對象,在C#語言中應(yīng)該有如下5種C#數(shù)組復(fù)制方法來復(fù)制。
C#數(shù)組復(fù)制方法一:使用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];
- }
C#數(shù)組復(fù)制方法二:使用數(shù)組對象中的CopyTo()方法
- int []pins = {9,3,7,2}
- int []copy2 = new int[pins.length];
- pins.CopyTo(copy2,0);
C#數(shù)組復(fù)制方法三:使用Array類的一個靜態(tài)方法Copy()
- int []pins = {9,3,7,2}
- int []copy3 = new int[pins.length];
- Array.Copy(pins,copy3,copy.Length);
C#數(shù)組復(fù)制方法四:使用Array類中的一個實例方法Clone()
可以一次調(diào)用,最方便,但是Clone()方法返回的是一個對象,所以要強制轉(zhuǎn)換成恰當?shù)念愵愋汀?/P>
- int []pins = {9,3,7,2}
- int []copy4 = (int [])pins.Clone();
C#數(shù)組復(fù)制方法五:
- 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ù)組,這個例子可以靈活變通,很多地方可以用。
C#數(shù)組復(fù)制方法的基本內(nèi)容就向你介紹到這里,希望對你了解和學習C#數(shù)組復(fù)制方法有所幫助。
【編輯推薦】