【问题标题】:Unexpected sub-type: MyNamespace.MyInheritedClass意外的子类型:MyNamespace.MyInheritedClass
【发布时间】:2013-02-01 21:56:57
【问题描述】:

在 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; }
}

【问题讨论】:

  • 我有一种预感 ProtoInclude 的工作方式正好相反——它似乎类似于 WCF 的 KnownType,而 this question 就是这样使用的。你的MapTrap 类应该包括反序列化器在使用基类型的属性时应该期望的所有子类型。

标签: c# serialization protocol-buffers protobuf-net


【解决方案1】:

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

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

[ProtoContract]
class TrapInstance : MapTrap {...}

【讨论】:

  • 如果我不想在基类中声明子类型怎么办?我试过这样做,但没有奏效
猜你喜欢
  • 2011-04-17
  • 1970-01-01
  • 2015-12-11
  • 1970-01-01
  • 1970-01-01
  • 2014-04-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多