使用Protobuf-net序列化object []

时间:2014-08-05 14:48:20

标签: c# protobuf-net

我想序列化和反序列化存储在对象数组中的一些值。

public class Sample
{
    public object[] Data;
}

我在运行时知道数组中期望的类型。实际上,我想将Sample中的Data视为消息流。

单独地,我知道我可以使用Serializer.NonGeneric.SerializeWithLengthPrefix使用PrefixStyle.Base128写出每个对象,并为Deserialise Type-Resolver创建一个Prefix-> Type map。见What is protobuf-net SerializeWithLengthPrefix tag argument for?

我正在努力实际上是让protobuf-net自动为我做这件事,然后将这种行为嵌入一个包含的消息中。据我所知,流中生成的消息将完全有效。

例如;假设我有这个对象数组:

new object[]
{
    "Hello",
    42,
    0.3529321,
    true
}

和tag-map

var typeToTag = new Dictionary<Type, int>()
{
    {typeof (string), 1},
    {typeof (int), 2},
    {typeof (double), 3},
    {typeof (bool), 4},
};

我可以使用非通用SerializeWithLengthPrefix

将它们写入流中
foreach (var value in data)
    Serializer.NonGeneric.SerializeWithLengthPrefix(
        stream,
        value,
        PrefixStyle.Base128,
        typeToTag[value.GetType()]);

现在,单独(独立存储)我知道该消息中有4个值,我知道(在运行时)地图

var tagToType = new Dictionary<int, Type>()
{
    {1, typeof (string)},
    {2, typeof (int)},
    {3, typeof (double)},
    {4, typeof (bool)},
};

然后我可以用

反序列化
var expectedElements = 4;

var readObjects = new object[expectedElements];

for (int i = 0; i < expectedElements; i++)   
    Serializer.NonGeneric.TryDeserializeWithLengthPrefix(
        stream,
        PrefixStyle.Base128,
        (t) => tagToType[t], out readObjects[i]);

    }
}

一切都很完美。

我的问题是我想捆绑上面的行为,以便当我尝试序列化和反序列化Sample的实例时,protobuf-net使用它(使用给定的标记映射序列化/反序列化对象流)带有嵌套消息流的消息。

欢迎任何指导我正确方向的帮助。 :)

0 个答案:

没有答案