c# - 使用 Protobuf-Net 序列化运行时消息合约

标签 c# protocol-buffers protobuf-net

假设我有一些数据

1: {
    1: 0.0
    2: 1
    3: "2"
    4: true
}

但是在编译时我不知道这个契约。然而,在运行时,我可以加载一个数据描述符,它告诉我我有多少个字段以及每个字段中的每种类型。即

new Type[]{
   typeof(double),
   typeof(int),
   typeof(string),
   typeof(bool)};

问:在运行时,如何获取 Protocol Buffer 以在给定数据描述的情况下从流中读取(和写入)消息?

我目前的想法是:在给定数据描述的情况下在运行时创建一个类型(发出),然后使用它进行 protocol-buf 序列化/反序列化。然后通过反射/动态访问属性。不确定这是否是个好主意。

这是来自 Serialize object[] with 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中没有其他的“adhoc object definition”API。但是,上面的变体适用于 Type 而不是泛型。

请注意,您没有继承Extensible;您也可以手动实现 IExtensibleExtensible 只是方便而已。请注意,IExtensible 除了已经在该类型上声明的任何 protobuf 字段之外。

关于c# - 使用 Protobuf-Net 序列化运行时消息合约,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25179186/

相关文章:

c# - Protobuf-Net 错误消息 : No Serializer defined for type: System. 类型

c# - 如果存在于 XmlNodeList C# 中的 XML 节点上

c# - 有没有一种方法可以在不逐行读取的情况下检索文件的最后一个字符?

rest - 在 gRPC 之上对 REST web 服务进行版本控制

machine-learning - caffe 中旧的 prototxt 语法

java - 高性能序列化 : Java vs Google Protocol Buffers vs . ..?

c# - 使用 protobuf-net 序列化数据集时出错

c# - Linq to XML 与 DOM

c# - 如何使用滚轮缩放

c# - 使用 protobuf-net 的惰性流驱动对象序列化