【发布时间】:2015-03-26 14:36:43
【问题描述】:
我正在使用 protobuf-net 序列化许多类型,其中一些是从基本类型继承的。我知道 Protocol Buffers 规范不支持继承,因此 protobuf-net 中的支持基本上是一种解决方法。
我没有使用 protobuf-net 属性,而是配置了自定义 RuntimeTypeModel,并使用了 Add 和 AddSubType 方法。我不太明白我应该如何确定将哪些数字用于传递给AddSubType 方法的字段编号(也就是将在ProtoInclude 属性中使用的数字)。
This SO question 和其他几个类似的并没有真正描述如何选择字段编号,实际上我已经看到了许多不同的变化:4 和 5; 7 & 8; 101 & 102 & 103; 20; 500;等等。显然他们被选中是为了不互相冲突,但是如何他们是被选中的?什么决定了从哪个数字开始?
以下代码是一个人为的示例,但它确实符合我的层次结构(具有两个派生子类型的基本 Event 类型)。
using System;
using System.Collections.Generic;
using ProtoBuf.Meta;
namespace Test
{
public sealed class History
{
public History()
{
Events = new List<Event>();
}
public ICollection<Event> Events { get; private set; }
}
public enum EventType
{
ConcertStarted, ConcertFinished, SongPlayed
}
public class Event
{
public EventType Type { get; set; }
public DateTimeOffset Timestamp { get; set; }
}
public sealed class Concert : Event
{
public string Location { get; set; }
}
public sealed class Song : Event
{
public string Name { get; set; }
}
public static class ModelFactory
{
public static RuntimeTypeModel CreateModel()
{
RuntimeTypeModel model = TypeModel.Create();
model.Add(typeof(DateTimeOffset), applyDefaultBehaviour: false)
.SetSurrogate(typeof(DateTimeOffsetSurrogate));
model.Add(typeof(History), applyDefaultBehaviour: false)
.Add("Events");
model.Add(typeof(Concert), applyDefaultBehaviour: false)
.Add("Location");
model.Add(typeof(Song), applyDefaultBehaviour: false)
.Add("Name");
model.Add(typeof(Event), applyDefaultBehaviour: false)
.Add("Type", "Timestamp")
.AddSubType(???, typeof(Concert))
.AddSubType(???, typeof(Song));
return model;
}
}
}
【问题讨论】:
标签: c# inheritance protobuf-net