且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

protobuf的和List<对象> - 如何序列化/反序列化?

更新时间:2022-06-20 21:41:04

(披露:我protobuf网的作者)

(disclosure: I'm the author of protobuf-net)

的BinaryFormatter 是一个基于元数据的串行器;也就是说,它发送关于序列中的每个对象的.NET类型信息。 protobuf网是一个基于合同的序列化(的XmlSerializer / 的DataContractSerializer 的等效二进制数,这也将拒绝此)

BinaryFormatter is a metadata-based serializer; i.e. it sends .NET type information about every object serialized. protobuf-net is a contract-based serializer (the binary equivalent of XmlSerializer / DataContractSerializer, which will also reject this).

目前没有任何机制来传送的任意的对象,因为另一端会有的没有办法的知道你要发送什么;但是,如果你有一个的组已知不同的的对象,你要发送的类型,有可能的选择。这里也工作在流水线允许运行时的可扩展架构(而不仅仅是属性,它是固定在编译) - 但这还远远没有完成。

There is no current mechanism for transporting arbitrary objects, since the other end will have no way of knowing what you are sending; however, if you have a known set of different object types you want to send, there may be options. There is also work in the pipeline to allow runtime-extensible schemas (rather than just attributes, which are fixed at build) - but this is far from complete.


这是不理想,但它的工作原理......它应该是比较容易的时候我已经完成了支持运行时模式的工作:

This isn't ideal, but it works... it should be easier when I've completed the work to support runtime schemas:

using System;
using System.Collections.Generic;
using ProtoBuf;
[ProtoContract]
[ProtoInclude(10, typeof(DataItem<int>))]
[ProtoInclude(11, typeof(DataItem<string>))]
[ProtoInclude(12, typeof(DataItem<DateTime>))]
[ProtoInclude(13, typeof(DataItem<Foo>))]
abstract class DataItem {
    public static DataItem<T> Create<T>(T value) {
        return new DataItem<T>(value);
    }
    public object Value {
        get { return ValueImpl; }
        set { ValueImpl = value; }
    }
    protected abstract object ValueImpl {get;set;}
    protected DataItem() { }
}
[ProtoContract]
sealed class DataItem<T> : DataItem {
    public DataItem() { }
    public DataItem(T value) { Value = value; }
    [ProtoMember(1)]
    public new T Value { get; set; }
    protected override object ValueImpl {
        get { return Value; }
        set { Value = (T)value; }
    }
}
[ProtoContract]
public class Foo {
    [ProtoMember(1)]
    public string Bar { get; set; }
    public override string ToString() {
        return "Foo with Bar=" + Bar;
    }
}
static class Program {
    static void Main() {
        var items = new List<DataItem>();
        items.Add(DataItem.Create(12345));
        items.Add(DataItem.Create(DateTime.Today));
        items.Add(DataItem.Create("abcde"));
        items.Add(DataItem.Create(new Foo { Bar = "Marc" }));
        items.Add(DataItem.Create(67890));

        // serialize and deserialize
        var clone = Serializer.DeepClone(items);
        foreach (DataItem item in clone) {
            Console.WriteLine(item.Value);
        }
    }
}