C# 使用Protobuf产生的堆栈溢出问题 Stack overflow.

直接说明情况:

[ProtoBuf.ProtoContract]
[ProtoBuf.ProtoInclude(11, typeof(Cat))]
[ProtoBuf.ProtoInclude(12, typeof(Dog))]
public abstract class Animal
{
[ProtoBuf.ProtoMember(1)]
public string name;
[ProtoBuf.ProtoMember(2)]
public int sex;
}

[ProtoBuf.ProtoContract]
public class Cat : Animal
{
[ProtoBuf.ProtoMember(1)]
public int value1;
}

[ProtoBuf.ProtoContract]
public class Dog : Animal
{
[ProtoBuf.ProtoMember(1)]
public int value1;
[ProtoBuf.ProtoMember(2)]
public int value2;
}

[ProtoBuf.ProtoContract]
public class Role
{
[ProtoBuf.ProtoMember(1)]
public Animal animal = new Dog();
}

声明以上类,其中Cat,Dog都继承于Animal,然后在Role中声明一个Animal类,并给予初始值new Dog()
说明Role默认情况下animal就是Dog
然后执行以下方法:
private static void Test()
{
Role role = new Role();
role.animal = new Cat();
var buffer = ProtobufSerialize.Serialize(role);
var role2 = ProtobufSerialize.Deserialize(buffer);
}
即改变Role中animal变量类型为Cat,会导致Protobuf序列化产生Stack overflow.堆栈溢出的问题

解决方法:

如果一个类型的某个变量或者字段需要序列化,且该字段是一个父类,则不能给定初始对象
即将Role类型改为一下写法
[ProtoBuf.ProtoContract]
public class Role
{
[ProtoBuf.ProtoMember(1)]
public Animal animal;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值