C#Google.ProtocolBuffers反序列化方法(proto3) [英] C# Google.ProtocolBuffers Deserialization Method (proto3)

查看:327
本文介绍了C#Google.ProtocolBuffers反序列化方法(proto3)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近升级了我的代码库(Java,C ++和C#)以使用proto3。对于C#,涉及到2000多次代码更改。这主要是语义上的,一切都很好,但是有一个我似乎无法理解的问题。序列化/反序列化。我有以下经修正的方法来对我的 IMessage 类型进行反序列化(注释在proto2中执行此操作的代码),这是GitHub存储库中示例中显示的代码...

I have recently upgraded my code base (Java, C++ and C#) to use proto3. In the case of C# this has involved over 2000 changes to the code. This is mostly semantic and all good, but there is one issue I can't seem to fathom; serialization/deserialization. I have the following amended method to desearialize my IMessage types (the code to do this in proto2 is commented), this is the code that is show in the examples within the GitHub repository...

public static T ToObject<T>(this byte[] buf) where T : IMessage 
{
    if (buf == null)
        return default(T);

    using (MemoryStream ms = new MemoryStream())
    {
        ms.Write(buf, 0, buf.Length);
        ms.Seek(0, SeekOrigin.Begin);

        MessageParser parser = new MessageParser();
        return (T)parser.ParseFrom(ms);
            //ProtoBuf.Serializer.Deserialize<T>(ms);
    }
}

但行 MessageParser解析器= new MessageParser(); 给我一个设计/编译时错误

but the line MessageParser parser = new MessageParser(); is giving me a design/compile-time error


MessageParser不包含包含0个参数的构造函数

MessageParser does not contain a constructor that contains 0 aguments

我对 proto3文档告诉我与此相反。

Well that is curious as I know about proto3 documents that tell me the contrary.

我想知道的是,使用proto3,我如何执行反序列化?

All I want to know is, using proto3, how I can perform my deserialization?

感谢您的时间。

注意,我的序列号是

public static byte[] ToByteArray<T>(this T o) where T : IMessage 
{
    if (o == null)
        return null;

    using (MemoryStream ms = new MemoryStream())
    {
        o.WriteTo(ms);
        return ms.ToArray();
    }
}

这可以编译,但是对吗?

This compiles, but is it right?

推荐答案

对于反序列化编译时错误,请文档告诉您应传递<$ c code>作为函数工厂,为 MessageParser< T> 的构造函数创建 T 实例

For your deserialization compile time error, the documentation told that you should pass a Func<T> as a function factory to create instances of T to the constructor of MessageParser<T>.

可能是()=>新的T()或更复杂的函数,具体取决于创建消息所需的内容。

It could be () => new T() or a more complicated function depending on what it needs to create your messages.

完整代码:

public static T ToObject<T>(this byte[] buf) where T : IMessage<T>, new()
{
    if (buf == null)
        return default(T);

    using (MemoryStream ms = new MemoryStream())
    {
        ms.Write(buf, 0, buf.Length);
        ms.Seek(0, SeekOrigin.Begin);

        MessageParser<T> parser = new MessageParser<T>(() => new T());
        return parser.ParseFrom(ms);
    }
}

作为文档说,序列化应该可以。

As the documentation says the serialization should be ok.

这篇关于C#Google.ProtocolBuffers反序列化方法(proto3)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆