Protobuf-net:使用 Stream 数据成员序列化第 3 方类

2023-12-05

如何序列化类的 Stream(或更准确地说是 Stream 派生的)数据成员?

假设我们有一个无法归因的第三方类:

public class Fubar
{
    public Fubar() { ... }
    public string Label { get; set; }
    public int DataType { get; set; }
    public Stream Data { get; set; } // Where it's always actually MemoryStream
};

我正在尝试使用 protobuf-net 来序列化该类。解决我提出的例外情况和各种SO问题:

RuntimeTypeModel.Default.Add(typeof(Stream), true)
    .AddSubType(1, typeof(MemoryStream));
RuntimeTypeModel.Default.Add(typeof(Fubar), false)
    .Add(1, "Label")
    .Add(2, "DataType")
    .Add(3, "Data");

using (MemoryStream ms = new MemoryStream())
{
    Fubar f1 = new Fubar();
    /* f1 initialized */

    // Serialize f1
    Serializer.SerializeWithLengthPrefix<Message>(ms, f1, PrefixStyle.Base128);

    // Now let's de-serialize
    ms.Position = 0;
    Fubar f2 = Serializer.DeserializeWithLengthPrefix<Fubar>(ms, PrefixStyle.Base128);
}

以上运行没有错误。 f2 中的 Label 和 DataType 是正确的,但 Data 变量只是一个空流。调试代码我发现内存流大约有 29 个字节(而 f1 本身的数据流超过 77KiB)。

我觉得好像我错过了一些相当微不足道的东西,但似乎无法弄清楚它会是什么。我认为确实可以序列化流数据成员。我是否还必须以某种方式指定 Stream 或 MemoryStream 类型的数据属性?


Stream是一个非常复杂的野兽,并且没有内置的序列化机制。您的代码将其配置为没有有趣成员的类型,这就是它返回为空的原因。

对于这种情况,我可能会创建一个代理,并使用以下命令进行设置:

RuntimeTypeModel.Default.Add(typeof(Fubar), false)
       .SetSurrogate(typeof(FubarSurrogate));

where:

[ProtoContract]
public class FubarSurrogate
{
    [ProtoMember(1)]
    public string Label { get; set; }
    [ProtoMember(2)]
    public int DataType { get; set; }
    [ProtoMember(3)]
    public byte[] Data { get; set; }

    public static explicit operator Fubar(FubarSurrogate value)
    {
        if(value == null) return null;
        return new Fubar {
            Label = value.Label,
            DataType = value.DataType,
            Data = value.Data == null ? null : new MemoryStream(value.Data)
        };
    }
    public static explicit operator FubarSurrogate(Fubar value)
    {
        if (value == null) return null;
        return new FubarSurrogate
        {
            Label = value.Label,
            DataType = value.DataType,
            Data = value.Data == null ?
                 null : ((MemoryStream)value.Data).ToArray()
        };
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Protobuf-net:使用 Stream 数据成员序列化第 3 方类 的相关文章

随机推荐