0
点赞
收藏
分享

微信扫一扫

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

烟中雯城 2022-02-15 阅读 95

直接说明情况:

[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 条评论