protobuf-net的prepareserializer有什么作用?

Car*_*los 4 serialization protobuf-net

我假设它看着你的模型,并以某种方式准备好了,所以你的前几个序列化不会减慢.如果我的消息传递模型有一个带有子类的消息类怎么办?将我的父类放在类型参数中也会为所有孩子做好准备吗?

Mar*_*ell 6

(这个答案假定为protobuf-net v2)

如果你的意思是Serializer.PrepareSerializer<T>(),它肯定会检查所有子类型,因此将为它们准备类型模型(意思是:它将找出需要序列化的字段/属性等).它将预编译(即IL-emit)类的代码,但(查看代码)不是专门为派生类型.如果无人参与,派生类型将在首次需要时自行编译.我认为!如果你真的想要,我可以做一个彻底的检查.

但是,如果你使用RuntimeTypeModel.Default.CompileInPlace()它,它会构建整个模型 - 所有已知的东西都准备好了.当然,这就让人们不得不首先告诉模型他们的困境; p

我会仔细检查以确定子类型序列化器准备在哪一点,只是为了确定.级联它们可能确实有意义.


更新:

它看起来确实级联到派生类型,但不是类型(如果有):

    [Test]
    public void CheckTypeSpecificCompileInPlaceCascadesToBaseAndChildTypes()
    {
        var model = TypeModel.Create();
        model[typeof(B)].CompileInPlace();

        Assert.IsTrue(model.IsPrepared(typeof(D)), "D"); // sub-sub-type
        Assert.IsTrue(model.IsPrepared(typeof(C)), "C"); // sub-type
        Assert.IsTrue(model.IsPrepared(typeof(B)), "B"); // self
        Assert.IsTrue(model.IsPrepared(typeof(A)), "A"); // base-type
    }

    [Test]
    public void CheckGlobalCompileInPlaceCascadesToBaseAndChildTypes()
    {
        var model = TypeModel.Create();
        model.Add(typeof (B), true); // give the model a clue!
        model.CompileInPlace();

        Assert.IsTrue(model.IsPrepared(typeof(D)), "D"); // sub-sub-type
        Assert.IsTrue(model.IsPrepared(typeof(C)), "C"); // sub-type
        Assert.IsTrue(model.IsPrepared(typeof(B)), "B"); // self
        Assert.IsTrue(model.IsPrepared(typeof(A)), "A"); // base-type
    }
Run Code Online (Sandbox Code Playgroud)

在这里,第二次测试通过; 第一次测试未引用"A" - 因此子类型("C"和"D")已完全编译.由于基类型仍然可以根据需要进行编译,因此这可能很好,但如果有用的话,我可能会将其划分为祖先类型.

(该IsPrepared方法仅存在于我的本地副本中)