我正在使用 Protobuf.net 序列化一些类。我希望能够序列化 SuperHero 类(如下),而不必在基类上指定 [ProtoInclude]。这是因为派生类是自动生成的,而基类不是,所以基类不直接知道它的派生类。
[ProtoContract]
class Person
{
[ProtoMember(1)]
public int Id { get; set; }
[ProtoMember(2)]
public string Name { get; set; }
}
[ProtoContract]
class SuperHero : Person
{
[ProtoMember(3)]
public string Powers { get; set; }
}
我使用的是最新版本的 protobuf.net。
最佳答案
首先要注意:在某些时候,您的代码必须知道子类 - 可能通过配置。重要的是,以某种方式您能够可靠地为每个子类型重现数字。如果您将数据存储到磁盘等,则在运行时发现类型时增加计数器是不够的,因为下次运行时您可能找不到相同顺序的类型。所以;让我们假设通过某种机制您有一个唯一的正整数,将 SuperHero 表示为 Person 的子类:
int tag = 7; // why not
Type subType = typeof(SuperHero);
然后,将此子类型告知 protobuf-net:
RuntimeTypeModel.Default.Add(typeof(Person), true).AddSubType(tag, subType);
这等同于属性处理代码在看到 [ProtoInclude(...)]
时所做的事情
关于c# - Protocol Buffer .net : how to handle inheritance without [ProtoInclude],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11869467/