我有一个 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/