2

I have the exception Unexpected sub-type: UnnamedGameServer.TrapInstance while Serializing in protobuf-net.

This is the code:

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; }
}
Pacha
  • 1,438
  • 3
  • 23
  • 46
  • I have a hunch `ProtoInclude` works the other way around - it seems similar to WCF's `KnownType`, and [this question](http://stackoverflow.com/questions/947666/what-does-the-protoinclude-attribute-mean-in-protobuf-net) uses it that way. Your `MapTrap` class should include all the subtypes the deserialiser should expect whenever working with a property of the base type. – millimoose Feb 01 '13 at 21:58

1 Answers1

1

The base-class needs to be told about the sub-classes, not the other way around. From a sub-class it is trivial to look for the base-class, since that is readily available at runtime.

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

[ProtoContract]
class TrapInstance : MapTrap {...}
Asheh
  • 1,547
  • 16
  • 25
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • What if I don't want to do declare sub types in base class? I tried doing this and it did not work – teeboy Jul 10 '21 at 16:03