用Protobuf-Net序列化一个运行时消息契约
本文关键字:一个 运行时 消息 契约 Protobuf-Net 序列化 | 更新日期: 2023-09-27 18:16:58
假设我有一些数据
1: {
1: 0.0
2: 1
3: "2"
4: true
}
但是在编译时我不知道合同。然而,在运行时,我可以加载一个数据描述符,它告诉我有多少字段以及每个字段中的每种类型是什么。例如
new Type[]{
typeof(double),
typeof(int),
typeof(string),
typeof(bool)};
Q:我怎么能,在运行时,得到协议,但读取(和写入)消息从给定的数据描述流?
我目前的想法是这样的:在运行时创建一个类型(发出)给出数据描述,然后有协议-但序列化/反序列化。然后通过反射/动态访问属性。但我不确定这是否是个好主意。
这是与Protobuf-net
我想知道你最好的选择可能只是使用扩展成员API;就像
[TestFixture]
public class SO25179186
{
[Test]
public void RuntimeMessageContract()
{
var adhoc = new AdHoc();
Extensible.AppendValue<double>(adhoc, 1, 0.0);
Extensible.AppendValue<int>(adhoc, 2, 1);
Extensible.AppendValue<string>(adhoc, 3, "2");
Extensible.AppendValue<bool>(adhoc, 4, true);
var clone = Serializer.DeepClone(adhoc);
Assert.AreNotSame(clone, adhoc);
Assert.AreEqual(0.0, Extensible.GetValue<double>(clone, 1));
Assert.AreEqual(1, Extensible.GetValue<int>(clone, 2));
Assert.AreEqual("2", Extensible.GetValue<string>(clone, 3));
Assert.AreEqual(true, Extensible.GetValue<bool>(clone, 4));
}
[ProtoContract]
class AdHoc : Extensible {}
}
目前在protobuf-net中没有其他的"特设对象定义"API。但是,上面的变体可以用于Type
而不是泛型。
注意,你没有从Extensible
继承;也可以手动实现IExtensible
。Extensible
只是很方便地做到了。注意,IExtensible
除了已经在该类型上声明的任何protobuf字段之外,还工作。