我想序列化和反序列化存储在对象数组中的一些值。
public class Sample
{
public object[] Data;
}
我知道在运行时数组中期望什么类型。实际上,我想将 Sample 内部的数据视为消息流。
就个人而言,我知道我可以使用Serializer.NonGeneric.SerializeWithLengthPrefix
使用a写出每个对象PrefixStyle.Base128
并为反序列化类型解析器创建一个前缀->类型映射。看protobuf-net SerializeWithLengthPrefix 标记参数的用途是什么? https://stackoverflow.com/questions/8601647/what-is-protobuf-net-serializewithlengthprefix-tag-argument-for
我正在努力解决的问题实际上是让 protobuf-net 自动为我执行此操作,然后将该行为嵌套在一个包含的消息中。据我所知,流中的结果消息将是完全有效的。
例如;假设我有这个对象数组:
new object[]
{
"Hello",
42,
0.3529321,
true
}
和标签映射
var typeToTag = new Dictionary<Type, int>()
{
{typeof (string), 1},
{typeof (int), 2},
{typeof (double), 3},
{typeof (bool), 4},
};
我可以使用非泛型将它们中的每一个写入流SerializeWithLengthPrefix
foreach (var value in data)
Serializer.NonGeneric.SerializeWithLengthPrefix(
stream,
value,
PrefixStyle.Base128,
typeToTag[value.GetType()]);
现在,单独(独立存储)我知道该消息中有 4 个值,并且我知道(在运行时)地图
var tagToType = new Dictionary<int, Type>()
{
{1, typeof (string)},
{2, typeof (int)},
{3, typeof (double)},
{4, typeof (bool)},
};
然后我可以反序列化
var expectedElements = 4;
var readObjects = new object[expectedElements];
for (int i = 0; i < expectedElements; i++)
Serializer.NonGeneric.TryDeserializeWithLengthPrefix(
stream,
PrefixStyle.Base128,
(t) => tagToType[t], out readObjects[i]);
}
}
这一切都很完美。
我的问题是我想捆绑上述行为,以便当我尝试序列化和反序列化实例时,protobuf-net 使用它(使用给定的标签映射序列化/反序列化对象流)Sample
- 实际上是具有嵌套消息流的消息。
欢迎任何帮助我走向正确方向的帮助。 :)