首頁  >  文章  >  後端開發  >  c#中數組賦值方法

c#中數組賦值方法

高洛峰
高洛峰原創
2016-12-16 14:50:012108瀏覽

C#中數組複製有多種方法

數組間的複製,int[] pins = {9,3,4,9};int [] alias = pins;這裡出了錯誤,也是錯誤的根源,以上代碼並沒有出錯,但根本不是複製,因為pins和alias都是引用,存在於堆疊中,而資料9,3,4,3是一個int物件存在於堆中,int [] alias = pins;只不過是創建另一個引用,alias和pins同時指向{9,3,4,3},當修改其中一個引用的時候,勢必影響另一個。複製的意思是新建一個和被複製對像一樣的對象,在C#語言中應該有以下4種方法來複製。

方法一:使用for循環

 

int []pins = {9,3,7,2}

int []copy = new int[pins.length];

int []copy = new int[pins.length];

for(int i =00; i!=copy.length;i++)

{

copy[i] = pins[i];

}

 

方法二:使用陣列物件中的CopyToe()方法pins = {9,3,7,2}

int []copy2 = new int[pins.length];

pins.CopyTo(copy2,0);

 

方法三:使用靜態方法三:使用靜態方法三:使用靜態使用方法Copy()

 

int []pins = {9,3,7,2}

int []copy3 =​​ new int[pins.length];

Array.Copy(pins,copy3,copy.Length );

 

方法四:使用Array類別中的一個實例方法Clone(),可以一次調用,最方便,但是Clone()方法返回的是一個對象,所以要強制轉換成恰當的類別類型。

 

int []pins = {9,3,7,2}

int []copy4 = (int [])pins.Clone();

 

方法。 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)

         

}

foreach (string s2 in student2)

{

      student.Add(s2);

}

string[] copyAfterl (

兩個數字組合並,最後把合併後的結果賦給copyAfter數組,這個例子可以靈活變通,很多地方可以用

更多 c#中數組賦值方法相關文章請關注PHP中文網!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn