可能重复:
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...
}