【发布时间】:2017-07-28 08:23:25
【问题描述】:
我正在使用反射在运行时为 protobuf-net 构建运行时模型,而无需注释我需要序列化的类。
我需要序列化的一些类使用继承,当然我想要基类的所有属性。
protobuf-net 默认不抓取继承树,所以你需要告诉它基类。所以我写了一小段代码来做到这一点:
public class InheritanceTest
{
public static string CreateProto()
{
var model = ProtoBuf.Meta.RuntimeTypeModel.Default;
var type = typeof(SubClass);
if (null != type.BaseType && type.BaseType != typeof(Object))
{
var hierarchy = new List<Type> { type };
var baseType = type.BaseType;
while (null != baseType)
{
if (baseType != typeof(Object))
{
hierarchy.Add(baseType);
}
baseType = baseType.BaseType;
}
hierarchy.Reverse();
var metaType = model.Add(hierarchy.First(), true);
for (int i = 1; i < hierarchy.Count; i++)
{
model.Add(hierarchy[i], true);
metaType = metaType.AddSubType(i, hierarchy[i]);
}
}
else
{
model.Add(type, true);
}
var properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance).OrderBy(p => p.Name);
var tagNumber = 1;
foreach (var propertyInfo in properties)
{
model[type].Add(tagNumber, propertyInfo.Name);
tagNumber++;
}
var schema = model.GetSchema(type, ProtoSyntax.Proto3);
return schema;
}
}
public class BaseClass
{
public string StringPropOnBaseClass { get; set; }
}
public class SubClass : BaseClass
{
public string StringPropOnSubClass { get; set; }
}
这会产生一个像这样的 .proto 文件:
syntax = "proto3";
package ProtoBufferSerializerTest;
message BaseClass {
// the following represent sub-types; at most 1 should have a value
optional SubClass SubClass = 1;
}
message SubClass {
string StringPropOnBaseClass = 1;
string StringPropOnSubClass = 2;
}
为什么 BaseClass 包含在 .proto 文件中?没有理由需要将其引入公共电汇格式。
有没有办法告诉运行时模型不要将其包含在 .proto 文件中?
BR
【问题讨论】:
标签: c# serialization protocol-buffers protobuf-net