C# 3.0 将类转换为字节数组+;C#
如何在C#中将类转换为字节数组。这是一个托管代码,因此以下代码失败C# 3.0 将类转换为字节数组+;C#,c#-3.0,C# 3.0,如何在C#中将类转换为字节数组。这是一个托管代码,因此以下代码失败 int objsize = System.Runtime.InteropServices.Marshal.SizeOf(objTimeSeries3D); byte[] arr = new byte[objsize]; IntPtr buff = System.Runtime.InteropServices.Marshal.AllocHGlobal(objsize); System.Runtime.InteropServices
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);
谢谢您可以使用。请注意,您的类必须是这样才能工作的
private byte[] ToByteArray(object source)
{
var formatter = new BinaryFormatter();
using (var stream = new MemoryStream())
{
formatter.Serialize(stream, source);
return stream.ToArray();
}
}
为什么需要将类转换为字节数组?如果我们知道你要解决的问题,我们可能会有更好的解决方法。