如何在C#中将Class转换为字节数组.这是一个托管的,因此以下代码失败
int objsize = System.Runtime.InteropServices.Marshal.SizeOf(objTimeSeries3D);
byte[] arr = new byte[objsize];
IntPtr buff = System.Runtime.InteropServices.Marshal.AllocHGlobal(objsize);
System.Runtime.InteropServices.Marshal.StructureToPtr(objTimeSeries3D, buff, true);
System.Runtime.InteropServices.Marshal.Copy(buff, arr, 0, objsize);
System.Runtime.InteropServices.Marshal.FreeHGlobal(buff);
Run Code Online (Sandbox Code Playgroud)
谢谢
Iga*_*nik 13
你可以用BinaryFormatter.请注意,您的课程必须[Serializable]为此工作.
private byte[] ToByteArray(object source)
{
var formatter = new BinaryFormatter();
using (var stream = new MemoryStream())
{
formatter.Serialize(stream, source);
return stream.ToArray();
}
}
Run Code Online (Sandbox Code Playgroud)