简体   繁体   English

序列化动态类型参数Protobuf-net

[英]Serializing dynamic type parameter Protobuf-net

Possible duplicates without answers: here and here . 没有答案的可能重复项: 此处此处

I am trying to serialize a class with a params object array using protobuf-net (2.0.0.668). 我正在尝试使用protobuf-net(2.0.0.668)将带有params对象数组的类序列化。

There can be different types in my params object[]. 我的params object []中可以有不同的类型。

When using DataContractSerializer, simply using [KnownType] works like expected. 使用DataContractSerializer时,只需使用[KnownType]像预期的那样工作。

I understand that it isn't the case for protobuf-net, and that I must use [ProtoInclude] instead, along with DynamicType = true , like so: 我了解protobuf-net并非如此,我必须改为使用[ProtoInclude]以及DynamicType = true ,如下所示:

[ProtoContract, ProtoInclude(20, typeof(Int32))] //Int32 as an example
public class MyParams 
{
    public MyParams(){}

    public MyParams(
        string name,
        params object[] parms)
    {
        this.Name = name;
        this.Parms = parms;
    }

    [ProtoMember(1)]
    public string Name { get; set; }

    [ProtoMember(2, DynamicType = true)]
    public object[] Parms { get; set; }
}

Strangely this work whenever I pass some strings in the object array but it fails if I give it anything else (Int32 in this example). 奇怪的是,每当我在对象数组中传递一些字符串时,这项工作就会完成,但是如果我给它其他任何东西,它都会失败(在本示例中为Int32)。

This is the exception it is throwing: 这是它抛出的异常:

Exception:Thrown: "Dynamic type is not a contract-type: Int32 (System.InvalidOperationException)

What am I missing? 我想念什么?

Thanks! 谢谢!

The current implementation of Dynamic type does not support primitives. Dynamic type的当前实现不支持原语。 It only supports contract types (other classes which have are somehow defined as ProtoContract ). 它仅支持合同类型(其他以某种方式定义为ProtoContract )。

From the wiki : 维基

DynamicType - stores additional Type information with the type (by default it includes the AssemblyQualifiedName, although this can be controlled by the user). DynamicType-存储具有类型的其他Type信息(默认情况下,它包括AssemblyQualifiedName,尽管可以由用户控制)。 This makes it possible to serialize weak models, ie where object is used for property members, however currently this is limited to contract types (not primitives), and does not work for types with inheritance (these limitations may be removed at a later time). 这样就可以序列化弱模型,即在对象用于属性成员的情况下,但是当前仅限于合同类型(不是原语),并且不适用于具有继承的类型(这些限制可以在以后删除) 。 Like with AsReference, this uses a very different layout format 与AsReference一样,这使用了非常不同的布局格式

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM