将对象/结构转换为byte []而不进行序列化.我如何获得对象的大小. [英] Convert Object/Struct to byte[] without serialization. How can I get size of Object.
本文介绍了将对象/结构转换为byte []而不进行序列化.我如何获得对象的大小.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
你好!
1.我需要将Object或struct转换为byte [](array).
2.最近,我发现某些代码表面上可以将对象转换为字节数组.但是为此,有必要知道物体的尺寸.如何接收物体的大小?
对我而言,必须在内部使用类型为字符串"的结构!!!
提前表示感谢.
Hello!
1. I need to convert Object or struct to byte[](array).
2. Recently, I have found a certain code which ostensibly could convert object in a byte array. But for this purpose it was necessary to know the size of object. How can I receive the size of object?
It is necessary for me to use structure with type "string" inside!!!
Thankful in advance.
推荐答案
internal static StructureType ReadStructure<StructureType>(Stream Stream)
where StructureType : struct
{
int Length = Marshal.SizeOf(typeof(StructureType));
byte[] Bytes = new byte[Length];
Stream.Read(Bytes, 0, Length);
IntPtr Handle = Marshal.AllocHGlobal(Length);
Marshal.Copy(Bytes, 0, Handle, Length);
StructureType Result = (StructureType)Marshal.PtrToStructure(Handle, typeof(StructureType));
Marshal.FreeHGlobal(Handle);
return Result;
}
internal static void WriteStructure(object Structure, Stream Stream)
{
int Length = Marshal.SizeOf(Structure);
byte[] Bytes = new byte[Length];
IntPtr Handle = Marshal.AllocHGlobal(Length);
Marshal.StructureToPtr(Structure, Handle, true);
Marshal.Copy(Handle, Bytes, 0, Length);
Marshal.FreeHGlobal(Handle);
Stream.Write(Bytes, 0, Length);
}
这可能会帮助您:
http://social.msdn.microsoft.com/论坛/en-IE/clr/thread/96747ab7-7d89-4846-9e83-46f71b8ccc66 [
This might help you:
http://social.msdn.microsoft.com/Forums/en-IE/clr/thread/96747ab7-7d89-4846-9e83-46f71b8ccc66[^]
创建这样的类:
类MyClass
{
public int a;
公共字符串文本;
MyClass(){}//XmlSerializer必需的...
}
.........
.........
/*使用XmlSerializer代替使用BinaryFormatter.这个可以
即使没有标记为[Serializable],也可以使用
序列化一个类 限制,它只会保存公共字段并进行读写
属性,并且需要默认的构造函数.*/
公共静态字节[] ObjectToByteArray(Object obj//我们的类实例
)
{
如果(obj == null)
返回null;
System.Xml.Serialization.XmlSerializer bf =新的System.Xml.Serialization.XmlSerializer(obj.GetType());
MemoryStream ms =新的MemoryStream();
bf.Serialize(ms,obj);
返回ms.ToArray();
}
享受吧!
Create class like this:
class MyClass
{
public int a;
public string text;
MyClass() { } // Necessary for XmlSerializer...
}
.........
.........
/*Instead of using a BinaryFormatter, use the XmlSerializer. This one can
serialize a class even if it is not marked as [Serializable], with the
restriction that it will only save the public fields and read-write
properties, and that it requires a default constructor.*/
public static byte[] ObjectToByteArray(Object obj//Our class instance
)
{
if (obj == null)
return null;
System.Xml.Serialization.XmlSerializer bf = new System.Xml.Serialization.XmlSerializer(obj.GetType());
MemoryStream ms = new MemoryStream();
bf.Serialize(ms, obj);
return ms.ToArray();
}
Enjoy!!!
这篇关于将对象/结构转换为byte []而不进行序列化.我如何获得对象的大小.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文