C#和.NET:如何序列化结构转变为byte []数组,使用的BinaryWriter? [英] C# and .NET: How to serialize a structure into a byte[] array, using BinaryWriter?

查看:283
本文介绍了C#和.NET:如何序列化结构转变为byte []数组,使用的BinaryWriter?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何序列化一个相当复杂的结构成一个byte []数组,使用的BinaryWriter

How to serialize a rather complex structure into a byte[] array, using BinaryWriter?

更新:


  • 对于这项工作,每一个结构(与子结构?)必须用[Serializable]属性装饰。

  • For this to work, every structure (and sub-structure?) must be decorated with the [Serializable] attribute.

我不需要实现ISerializable接口,这样的设计给了自己的序列化对象的控制。

I do not need to implement the ISerializable interface, as this is designed to give an object control over its own serialization.

推荐答案

从评论中,OP的情况下,需要与应用程序/ .NET的未来版本兼容性强,在这种情况下,我总是提醒的 againt 的BinaryFormatter - 它有许多特色,根本不能很好地版本之间(而不是平台之间肯定)工作

From comments, the OP's scenario requires strong compatibility with future versions of the application / .NET, in which case I always advise againt BinaryFormatter - it has many "features" that simply don't work well between versions (and certainly not between platforms).

我建议在寻找基于合同的序列化;我有偏见,但我对protobuf网(映射到谷歌的protobuf的规范)倾斜。该的最简单的方式做到这一点是属性类型以这样的方式,库可以使他们的轻工作(尽管它也可以不带属性来完成),例如:

I recommend looking at contract-based serializers; I'm biased, but I lean towards protobuf-net (which maps to Google's protobuf specification). The easiest way to do this is to attribute the types in such a way that the library can make light work of them (although it can also be done without attributes), for example:

 [ProtoContract]
 public class Customer {
     [ProtoMember(1)]
     public List<Order> Orders {get {....}}

     [ProtoMember(2)]
     public string Name {get;set;}

     ... etc
 }

(属性appoach很熟悉,如果你做任何的XmlSerializer或DataContractSerializer的工作 - 事实上protobuf网可以消耗从这些属性,如果你不希望添加protobuf网特定的属性)

(the attribute appoach is very familiar if you've done any XmlSerializer or DataContractSerializer work - and indeed protobuf-net can consume the attributes from those if you don't want to add protobuf-net specific attributes)

则是这样的:

Customer cust = ...
byte[] data;
using(var ms = new MemoryStream()) {
    Serializer.Serialize(ms, cust);
    data = ms.ToArray();
}



这种方式生产的数据是独立的平台,并在任何匹配可以加载合同(它甚至不需要为客户 - 它可以在任何类型的通过属性布局相匹配)。事实上,在大多数情况下,它会很容易加载到任何其他的protobuf实施 - JAVA,C ++等

The data produced this way is platform independent, and could be loaded on any matching contract (it doesn't even need to be Customer - it could any type with matching layout via the attributes). Indeed, in most cases it'll load easily into any other protobuf implementation - Java, C++, etc.

这篇关于C#和.NET:如何序列化结构转变为byte []数组,使用的BinaryWriter?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆