您好,登錄后才能下訂單哦!
本文小編為大家詳細(xì)介紹“C#復(fù)制數(shù)組的方式有哪些”,內(nèi)容詳細(xì),步驟清晰,細(xì)節(jié)處理妥當(dāng),希望這篇“C#復(fù)制數(shù)組的方式有哪些”文章能幫助大家解決疑惑,下面跟著小編的思路慢慢深入,一起來學(xué)習(xí)新知識吧。
如果把一個變量值復(fù)制給另外一個數(shù)組變量,那么2個變量指向托管堆上同一個引用。
如果想在托管堆上創(chuàng)建另外的一份數(shù)組實(shí)例,通常使用Array.Copy方法。
class Program { static void Main(string[] args) { int[] a = {1, 3, 6}; int[] b =new int[a.Length]; Array.Copy(a,0,b,0,a.Length); MyArrCopy myArrCopy = new MyArrCopy(); myArrCopy.Display(a); Console.ReadKey(); } } public class MyArrCopy { public void Display(int[] arr) { for (int i = 0; i < arr.Length; i++) { if (i != 0) { Console.Write(","); } Console.Write(arr[i]); } } }
在數(shù)據(jù)量大的情況下,使用Buffer.BlockCopy方法將會擁有更高的復(fù)制效率。
分別測試使用Buffer.BlockCopy和Array.Copy的區(qū)別。
public class CopyTest { private int[] _myArr;//數(shù)組源 private int[] _blockArr=new int[10000];//使用 Buffer.BlockCopy的目標(biāo)數(shù)組 private int[] _copyArr=new int[10000];//使用Array.Copy的目標(biāo)數(shù)組 public CopyTest(int[] myArr) { _myArr = myArr; } public void TestBlockCopy() { Stopwatch sw = new Stopwatch(); sw.Start(); Buffer.BlockCopy(_myArr, 0,_blockArr,0,_myArr.Length); sw.Stop(); Console.WriteLine("使用Buffer.BlockCopy方法:" + sw.ElapsedTicks); } public void TestNormalCopy() { Stopwatch sw = new Stopwatch(); sw.Start(); Array.Copy(_myArr, 0, _copyArr,0, _myArr.Length); sw.Start(); Console.WriteLine("使用Array.Copy方法:" + sw.ElapsedTicks); } }
客戶端。
int[] a = new int[10000]; for (int i = 0; i < 10000; i++) { a[i] = i; } var copyTest = new CopyTest(a); copyTest.TestBlockCopy(); copyTest.TestNormalCopy(); Console.ReadKey();
讀到這里,這篇“C#復(fù)制數(shù)組的方式有哪些”文章已經(jīng)介紹完畢,想要掌握這篇文章的知識點(diǎn)還需要大家自己動手實(shí)踐使用過才能領(lǐng)會,如果想了解更多相關(guān)內(nèi)容的文章,歡迎關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。