我在运行时使用反射为我构建protobuf-net的运行时模型,而无需注释需要序列化的类。protobuf-net继承在.proto文件中显示基类
我需要序列化的一些类使用继承,当然我想要基类的所有属性。
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 flie中?
BR
感谢您的回答。我最初要求运行时模型在添加类型时应用默认行为,但这意味着我的.proto文件中没有获得任何基类属性。答案是告诉它不要应用默认行为。然后我根本不必担心基类。非常感谢! –
@JayPete如果你的类型没有装饰属性(protocontract,datacontract等),那么默认行为不存在*反正* –
很高兴知道!谢谢! –