本文實例講述了C#通過指針實現快速拷貝的方法。分享給大家供大家參考。具體實現方法如下:
// fastcopy.cs// 編譯時使用:/unsafeusing System;class Test{  // unsafe 關鍵字允許在下列  // 方法中使用指針:  static unsafe void Copy(byte[] src, int srcIndex, byte[] dst, int dstIndex, int count)  {    if (src == null || srcIndex < 0 ||      dst == null || dstIndex < 0 || count < 0)    {      throw new ArgumentException();    }    int srcLen = src.Length;    int dstLen = dst.Length;    if (srcLen - srcIndex < count || dstLen - dstIndex < count)    {      throw new ArgumentException();    }    // 以下固定語句固定    // src 對象和 dst 對象在內存中的位置,以使這兩個對象    // 不會被垃圾回收移動。    fixed (byte* pSrc = src, pDst = dst)    {      byte* ps = pSrc;      byte* pd = pDst;      // 以 4 個字節的塊為單位循環計數,一次復制      // 一個整數(4 個字節):      for (int n = 0; n < count / 4; n++)      {        *((int*)pd) = *((int*)ps);        pd += 4;        ps += 4;      }      // 移動未以 4 個字節的塊移動的所有字節,      // 從而完成復制:      for (int n = 0; n < count % 4; n++)      {        *pd = *ps;        pd++;        ps++;      }    }  }  static void Main(string[] args)  {    byte[] a = new byte[100];    byte[] b = new byte[100];    for (int i = 0; i < 100; ++i)      a[i] = (byte)i;    Copy(a, 0, b, 0, 100);    Console.WriteLine("The first 10 elements are:");    for (int i = 0; i < 10; ++i)      Console.Write(b[i] + " ");    Console.WriteLine("/n");  }}希望本文所述對大家的C#程序設計有所幫助。
新聞熱點
疑難解答