c# - ProtoBuf 不反序列化具有接口(interface)的对象

标签 c# sockets protobuf-net

我有一个 TCP 套接字,我想使用 ProtoBuf 发送和接收对象。但我收到了这个错误:

Exception thrown: 'System.InvalidOperationException' in protobuf-net.dll

Type is not expected, and no contract can be inferred: Server.Packet.IMsg


我的界面:
 public interface IMsg { }
我要发送和接收的对象之一:
[ProtoContract]
public class PacketPerson : IMsg
{
    [ProtoMember(1)]
    public string Name{ get; set; }
    [ProtoMember(2)]
    public string Country { get; set; }
}
我的套接字在获得完整缓冲区后试图反序列化:
 IMsg msg = Serialization.Desirialize(SocketMemoryStream);
去理想化:
    public static IMsg Desirialize(MemoryStream ms) // socket buffer
    {
        ms.Position = 0;
        return Serializer.Deserialize<IMsg>(ms);
    }

最佳答案

yes, but I want to send multi-object and to identify them by using "Type type = packet.GetType();" Then use If statement "if (type == typeof(PacketPerson))"



我的建议(以作者身份):


[ProtoContract]
[ProtoInclude(1, typeof(PacketPerson))]
// future additional message types go here
class SomeMessageBase {}

[ProtoContract]
class PacketPerson : SomeMessageBase
{
    [ProtoMember(1)]
    public string Name{ get; set; }
    [ProtoMember(2)]
    public string Country { get; set; }
}

并反序列化/序列化 <SomeMessageBase> .库将在这里以正确的方式处理所有继承。在幕后,这将类似于(在 .proto 术语中)实现:

message SomeMessageBase {
    oneof ActualType {
        PacketPerson = 1;
        // ...
    }
}
message PacketPerson {
    string Name = 1;
    string Country = 2;
}

您现在可以使用多态性或类型测试来确定运行时的实际类型。新switch语法特别有用:

SomeMessageBase obj = WhateverDeserialize();
switch(obj)
{
    case PacketPerson pp:
        // do something person-specific with pp
        break;
    case ...:
        // etc
        break;
}

关于c# - ProtoBuf 不反序列化具有接口(interface)的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57254443/

相关文章:

.net - Protobuf-net : ProtoInclude and compatibility 中的继承

c# - 何时不在 C#(或 Java、C++ 等)中使用 Regex

c# - 如何创建/实例化 'Type'的对象

c# - 在 TFS 或共享文件夹中存储内容图像以便在多个网站中使用的正确方法是什么?

java - AppInventor2 TCP 客户端扩展使应用程序崩溃

c# - 使用 ProtoBuf-Net 处理父子关系的最佳方式是什么

c# - 继承 .NET 的通用 Controller 类

linux - 守护进程 : closed stderr and accept(2)

objective-c - 使用 CFWriteStream 将文件传输到套接字

wcf - 使用 Protobuf-net 的端点行为配置 WCF