当尝试使用已通过反射加载的 proto 序列化程序序列化层次结构类型时,它似乎有一些奇怪的行为,并且似乎并没有真正起作用。
这是代码:
[ProtoContract]
[ProtoInclude(10, typeof(Derived))]
class Base
{
[ProtoMember(1)]
public string BaseFirstProperty { get; set; }
[ProtoMember(2)]
public string BaseSecProperty { get; set; }
}
[ProtoContract]
class Derived : Base
{
[ProtoMember(1)]
public string DerivedFirstProperty { get; set; }
}
static void Main(string[] args)
{
var assembly = Assembly.LoadFile(@"c:\protobuf-net.dll");
var derived = new Derived()
{
BaseFirstProperty = "BaseFirst",
BaseSecProperty = "BaseSec",
DerivedFirstProperty = "DerivedFirst"
};
var reflectionSerializer = assembly.GetType("ProtoBuf.Serializer");
var getTypeSerializer = typeof(Serializer);
var reflectionMethods = reflectionSerializer.GetMethods(BindingFlags.Static | BindingFlags.Public);
var reflectionGenericMethodInfo = reflectionMethods.First<MethodInfo>(method => method.Name == "SerializeWithLengthPrefix");
var reflectionSpecificMethodInfo = reflectionGenericMethodInfo.MakeGenericMethod(new Type[] { derived.GetType() });
var getTypeMethods = getTypeSerializer.GetMethods(BindingFlags.Static | BindingFlags.Public);
var getTypeGenericMethodInfo = getTypeMethods.First<MethodInfo>(method => method.Name == "SerializeWithLengthPrefix");
var getTypeSpecificMethodInfo = getTypeGenericMethodInfo.MakeGenericMethod(new Type[] { derived.GetType() });
var reflectionStream = new MemoryStream();
var getTypeStream = new MemoryStream();
reflectionSpecificMethodInfo.Invoke(null, new object[] { reflectionStream, derived, PrefixStyle.Base128 });
getTypeSpecificMethodInfo.Invoke(null, new object[] { getTypeStream, derived, PrefixStyle.Base128 });
Console.WriteLine(reflectionStream.ToArray().Length); // Prints out 15
Console.WriteLine(getTypeStream.ToArray().Length); // Prints out 37
}
据我所知,它应该是一样的......我做错了什么?请注意,我使用的是 Proto-buf 2.0.0.431。谢谢,