将类转换为字节数组+ C# [英] convert a class to byte array + C#
本文介绍了将类转换为字节数组+ C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在C#中将类转换为字节数组。这是一个托管对象,因此以下代码失败
How can I convert a Class to byte array in C#. This is a managed one so the following code is failing
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
。请注意,您的课程必须为 [可序列化]
。
You can use BinaryFormatter
. Note that your class must be [Serializable]
for this to work.
private byte[] ToByteArray(object source)
{
var formatter = new BinaryFormatter();
using (var stream = new MemoryStream())
{
formatter.Serialize(stream, source);
return stream.ToArray();
}
}
这篇关于将类转换为字节数组+ C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文