我在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; }
}
答案 0 :(得分:1)
基类需要被告知子类,而不是相反。从子类中,它是 trivial 来查找基类,因为它在运行时很容易获得。
[ProtoContract, ProtoInclude(5, typeof(TrapInstance))]
public class MapTrap {...}
[ProtoContract]
class TrapInstance : MapTrap {...}