我建议查看基于合约的序列化器;我有偏见,但我倾向于 protobuf-net (它映射到 Google 的 protobuf 规范)。最简单的方法是以这样的方式对类型进行属性设置,使库可以轻松地处理它们(尽管也可以在没有属性的情况下完成),例如:(
[ProtoContract]
public class Customer {
[ProtoMember(1)]
public List<Order> Orders {get {....}}
[ProtoMember(2)]
public string Name {get;set;}
... etc
}
From comments, the OP's scenario requires strong compatibility with future versions of the application / .NET, in which case I always advise againtBinaryFormatter - it has many "features" that simply don't work well between versions (and certainly not between platforms).
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
}
(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)
then something like:
Customer cust = ...
byte[] data;
using(var ms = new MemoryStream()) {
Serializer.Serialize(ms, cust);
data = ms.ToArray();
}
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.
public static byte[] XmlSerializeToByte<T>(T value) where T : class
{
if (value == null)
{
throw new ArgumentNullException();
}
XmlSerializer serializer = new XmlSerializer(typeof(T));
using (MemoryStream memoryStream = new MemoryStream())
{
using (XmlWriter xmlWriter = XmlWriter.Create(memoryStream))
{
serializer.Serialize(xmlWriter, value);
return memoryStream.ToArray();
}
}
}
public static T XmlDeserializeFromBytes<T> (byte[] bytes)
where T : class
{
if (bytes == null || bytes.Length == 0)
{
throw new InvalidOperationException();
}
XmlSerializer serializer = new XmlSerializer(typeof(T));
using (MemoryStream memoryStream = new MemoryStream(bytes))
{
using (XmlReader xmlReader = XmlReader.Create(memoryStream))
{
return (T)serializer.Deserialize(xmlReader);
}
}
}
//Serialize
Duck duck = new Duck() { Name = "Donald Duck" };
byte[] bytes = Test.XmlSerializeToByte(duck);
//Deserialize
var deDuck = Test.XmlDeserializeFromBytes<Duck>(bytes);
Console.WriteLine(deDuck.Name);
code snippet.
public static byte[] XmlSerializeToByte<T>(T value) where T : class
{
if (value == null)
{
throw new ArgumentNullException();
}
XmlSerializer serializer = new XmlSerializer(typeof(T));
using (MemoryStream memoryStream = new MemoryStream())
{
using (XmlWriter xmlWriter = XmlWriter.Create(memoryStream))
{
serializer.Serialize(xmlWriter, value);
return memoryStream.ToArray();
}
}
}
public static T XmlDeserializeFromBytes<T> (byte[] bytes)
where T : class
{
if (bytes == null || bytes.Length == 0)
{
throw new InvalidOperationException();
}
XmlSerializer serializer = new XmlSerializer(typeof(T));
using (MemoryStream memoryStream = new MemoryStream(bytes))
{
using (XmlReader xmlReader = XmlReader.Create(memoryStream))
{
return (T)serializer.Deserialize(xmlReader);
}
}
}
//Serialize
Duck duck = new Duck() { Name = "Donald Duck" };
byte[] bytes = Test.XmlSerializeToByte(duck);
//Deserialize
var deDuck = Test.XmlDeserializeFromBytes<Duck>(bytes);
Console.WriteLine(deDuck.Name);
发布评论
评论(3)
使用 BinaryFormatter 将对象序列化为字节[]。 BinaryWriter 仅用于将字节写入流。
Use the BinaryFormatter to serialize an object to a byte[]. BinaryWriter is just for writing bytes to a stream.
从评论来看,OP的场景需要与应用程序/.NET的未来版本具有很强的兼容性,在这种情况下,我总是建议反对
BinaryFormatter
- 它有许多“功能”,只需版本之间不能很好地工作(当然平台之间也不能很好地工作)。我建议查看基于合约的序列化器;我有偏见,但我倾向于 protobuf-net (它映射到 Google 的 protobuf 规范)。最简单的方法是以这样的方式对类型进行属性设置,使库可以轻松地处理它们(尽管也可以在没有属性的情况下完成),例如:(
属性 appoach 是如果您完成了任何 XmlSerializer 或 DataContractSerializer 工作,那么非常熟悉 - 事实上,如果您不想添加 protobuf-net 特定属性,protobuf-net 可以使用这些属性)
,然后类似于:
产生的数据way 是独立于平台的,并且可以加载到任何匹配的合约上(它甚至不需要是
Customer
- 它可以是通过属性具有匹配布局的任何类型)。事实上,在大多数情况下,它可以轻松加载到任何其他 protobuf 实现中 - Java、C++ 等。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).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:
(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)
then something like:
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.代码片段。
code snippet.