是否可以将protobuf序列化的内容直接写入SharpZipLib流?当我尝试执行此操作时,看起来所提供的流中未填充protobuf中的数据。稍后,我需要从提供的Zip流中获取反序列化的实体。
我的代码如下所示:

private byte[] ZipContent(T2 content)
    {
        const short COMPRESSION_LEVEL = 4; // 0-9
        const string ENTRY_NAME = "DefaultEntryName";


        byte[] result = null;

        if (content == null)
            return result;

        IStreamSerializerProto<T2> serializer = this.GetSerializer(content.GetType());
        using (MemoryStream outputStream = new MemoryStream())
        {
            using (ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream))
            {
                zipOutputStream.SetLevel(COMPRESSION_LEVEL);
                ZipEntry entry = new ZipEntry(ENTRY_NAME);
                entry.DateTime = DateTime.Now;
                zipOutputStream.PutNextEntry(entry);

                serializer.Serialize(zipOutputStream, content);
            }

            result = outputStream.ToArray();
        }

        return result;
    }

private class ProtobufStreamSerializer<T3> : IStreamSerializerProto<T3>
        {
            public ProtobufStreamSerializer()
            {
                ProtoBuf.Serializer.PrepareSerializer<T3>();
            }

    public void Serialize(Stream outputStream, T3 content)
    {
        Serializer.Serialize(outputStream, content);
    }

            public T3 Deserialize(Stream inputStream)
            {
                T3 deserializedObj;
                using (inputStream)
                {
                    deserializedObj = ProtoBuf.Serializer.Deserialize<T3>(inputStream);
                }
                return deserializedObj;
            }
        }


我要序列化的类的示例:

[Serializable]
    [ProtoContract]
    public class Model
    {
        [XmlElement("ModelCode")]
        [ProtoMember(1)]
        public int ModelCode { get; set; }

                ...

    }

最佳答案

我相信这是问题所在(在问题的原始代码中):

public void Serialize(Stream outputStream, T3 content)
{
    using (var stream = new MemoryStream())
    {
        Serializer.Serialize(stream, content);
    }
}


您完全忽略了outputStream,而是仅将数据写入新的MemoryStream,然后将其忽略。

我怀疑您只想要:

public void Serialize(Stream outputStream, T3 content)
{
    Serializer.Serialize(outputStream, content);
}


我还建议从您的using方法中删除Deserialize语句:我希望调用者在完成输入流后负责处理输入流。您的方法可以简化为:

public T3 Deserialize(Stream inputStream)
{
    return ProtoBuf.Serializer.Deserialize<T3>(inputStream);
}

关于c# - 如何将Protobuf序列化的内容直接写入SharpZipLib流,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19590932/

10-09 16:38