意外的子类型:MyNamespace.MyInheritedClass

本文关键字:MyNamespace MyInheritedClass 类型 意外 | 更新日期: 2023-09-27 17:56:58

我在protobuf-net中序列化时Unexpected sub-type: UnnamedGameServer.TrapInstance有例外。

这是代码:

class test
{
    void testMethod(PacketNewTrapResponse packet)
    {
        using (var stream = new MemoryStream())
        {
            Serializer.SerializeWithLengthPrefix<PacketNewTrapResponse>(stream, (PacketNewTrapResponse)packet, PrefixStyle.Base128);
        }
    }
}
[ProtoContract]
public class MapTrap
{
    [ProtoMember(1)]
    public IntegerVector2 Position;
    [ProtoMember(2)]
    public int TrapServerID;
    [ProtoMember(3)]
    public int LocationID;
}
[ProtoContract, ProtoInclude(1, typeof(MapTrap))]
class TrapInstance : MapTrap
{
    public TrapInstance(TrapProperties trap, SessionCharacter session, int serverTrapId, int locationId, IntegerVector2 position)
    {
        TrapServerID = serverTrapId;
        Trap = trap;
        Position = position;
        LocationID = locationId;
        OwnerOfTrap = session;
        LocationID = locationId;
        Position = position;
    }
    public SessionCharacter OwnerOfTrap { get; set; }
    public TrapProperties Trap { get; set; }
}

意外的子类型:MyNamespace.MyInheritedClass

基类需要被告知子类,而不是相反。从子类中查找基类是微不足道的,因为它在运行时很容易获得。

[ProtoContract, ProtoInclude(5, typeof(TrapInstance))]
public class MapTrap {...}
[ProtoContract]
class TrapInstance : MapTrap {...}