gpt4 book ai didi

c#-3.0 - 将类转换为字节数组 + C#

转载 作者:行者123 更新时间:2023-12-04 22:16:54 25 4
gpt4 key购买 nike

如何在 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.Marshal.StructureToPtr(objTimeSeries3D, buff, true);
System.Runtime.InteropServices.Marshal.Copy(buff, arr, 0, objsize);
System.Runtime.InteropServices.Marshal.FreeHGlobal(buff);

谢谢

最佳答案

您可以使用 BinaryFormatter 。请注意,您的类(class)必须是 [Serializable] 才能正常工作。

private byte[] ToByteArray(object source)
{
var formatter = new BinaryFormatter();
using (var stream = new MemoryStream())
{
formatter.Serialize(stream, source);
return stream.ToArray();
}
}

关于c#-3.0 - 将类转换为字节数组 + C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2689212/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com