protobuf.net v2.4.6可以正常工作,V3.0.29引发“一旦生成序列化器,就无法更改类型”

问题描述

protobuf.net 3.0。*在以编程方式为同时从classB继承并具有classB类型的字段的类创建runtimeTypeModel时,引发InvalidOperationException。在这种情况下,Protobuf.net v2.4.6不会发生。

在linqpad中创建的这个最小示例显示了问题。代码做错了吗?还是protobuf.net 3.0 +有问题?

class MyClass : AnotherClass
{
    public MyClass(AnotherClass ac) => _mem1 = ac;
    public AnotherClass _mem1;
}

class AnotherClass{}
                                                
RuntimeTypeModel MakeRTM( Type type)
{
    var model = RuntimeTypeModel.Create();
    MetaType MetaTypeOuter = model.Add(type,true);     
    Type baseType = type.BaseType;
    MetaType MetaTypeInner = model.Add(baseType,true);
    MetaTypeInner.AddSubType(1,type);
    
    int index = 0;
    foreach( var fld in type.GetFields() )
    {
        // model.CanSerialize freezes both MetaTypes,which causes the exception at "MetaTypeOuter.Add"
        if(!model.CanSerialize(fld.FieldType)) 
            model.Add(fld.FieldType,true); // not called,as model.CanSerialize returned true

        // throws invalidOperationException "The type cannot be changed once a serializer has been generated ..."
        MetaTypeOuter.Add(++index,fld.Name);
    }            
    
    return model;
}

void Main()
{
    var mgt = new MyClass(new AnotherClass());
    var rtmi = MakeRTM(mgt.GetType());
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)