我想序列化和反序列化存储在对象数组中的一些值.
public class Sample
{
public object[] Data;
}
Run Code Online (Sandbox Code Playgroud)
我在运行时知道在数组中期望什么类型.实际上,我想将Sample中的Data视为消息流.
单独地,我知道我可以使用a Serializer.NonGeneric.SerializeWithLengthPrefix来编写每个对象,PrefixStyle.Base128并为Deserialise Type-Resolver创建一个Prefix-> Type贴图.请参阅什么是protobuf-net SerializeWithLengthPrefix标记参数?
我正在努力的实际上是让protobuf-net自动为我做这件事,然后将这种行为嵌入一个包含的消息中.据我所知,流中生成的消息将完全有效.
例如; 假设我有这个对象数组:
new object[]
{
"Hello",
42,
0.3529321,
true
}
Run Code Online (Sandbox Code Playgroud)
和标签图
var typeToTag = new Dictionary<Type, int>()
{
{typeof (string), 1},
{typeof (int), 2},
{typeof (double), 3},
{typeof (bool), 4},
};
Run Code Online (Sandbox Code Playgroud)
我可以使用非泛型将它们写入流中 SerializeWithLengthPrefix
foreach (var value in data)
Serializer.NonGeneric.SerializeWithLengthPrefix(
stream,
value,
PrefixStyle.Base128,
typeToTag[value.GetType()]);
Run Code Online (Sandbox Code Playgroud)
现在,单独(独立存储)我知道该消息中有4个值,我知道(在运行时)地图
var tagToType = new Dictionary<int, Type>()
{
{1, typeof (string)},
{2, typeof (int)},
{3, typeof (double)},
{4, typeof (bool)},
};
Run Code Online (Sandbox Code Playgroud)
然后我可以反序列化
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]);
}
}
Run Code Online (Sandbox Code Playgroud)
这一切都很完美.
我的问题是我想捆绑上面的行为,以便protobuf-net使用它(使用给定的标记映射序列化/反序列化对象流)当我尝试序列化和反序列化一个实例时Sample- 实际上是一个带有嵌套消息流的消息.
欢迎任何帮助我指导正确方向的帮助.:)
| 归档时间: |
|
| 查看次数: |
2611 次 |
| 最近记录: |