可能重复:
C#:复制数组的任何更快的方法?
我有一个这样的结构数组:
struct S
{
public long A;
public long B;
}
...
S[] s1 = new S[1000000];
...
S[] = new S[s1.Length];
// Need to create a copy here.
我可以使用不安全模式并将结构的源数组复制到字节数组,然后从字节数组复制到结构的目标数组。但这意味着我将不得不分配一个巨大的中间字节数组。有没有办法避免这种情况?是否可以以某种方式将目标数组表示为字节数组并直接复制到那里?
unsafe
{
int size = Marshal.SizeOf(s0[0]) * s0.Length;
byte[] tmp = new byte[size];
fixed (var tmpSrc = &s0[0])
{
IntPtr src = (IntPtr)tmpSrc;
Marchal.Copy(tmpSrc, 0, tmp, 0, size);
}
// The same way copy to destination s1 array...
}