浅谈C#各种数组直接的数据复制/转换

2019-12-30 13:56:46于丽


public static T2[] Arr2Arr4<T1, T2>(T1[] from)
  where T1 : struct
  where T2 : struct
{
  int byteNum = from.Length * from[0].Sizeof();
  T2 testByte = new T2();
  T2[] dTo = new T2[byteNum / testByte.Sizeof()];

  Buffer.BlockCopy(from, 0, dTo, 0, byteNum);

  return dTo;
}

测试部分代码:


byte[] from = new byte[100];
from[0] = 1;
from[1] = 1;

var last = DateTime.Now;
for (int i = 0; i < 2000000; i++)
{
  。。。
}
Console.WriteLine((DateTime.Now- last).TotalMilliseconds);

//sizeof扩展方法internal static class ExFunc
{
  public static int Sizeof(this ValueType t)
  {
    return Marshal.SizeOf(t);
  }
}

综上所述,Buffer.BlockCopy 适用场合最广泛,效率最高。

以上这篇浅谈C#各种数组直接的数据复制/转换就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持ASPKU。


注:相关教程知识阅读请移步到c#教程频道。