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).

There can be different types in my params object[].

When using DataContractSerializer, simply using [KnownType] works like expected.

I understand that it isn't the case for protobuf-net, and that I must use [ProtoInclude] instead, along with DynamicType = true, like so:

[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).

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. It only supports contract types (other classes which have are somehow defined as 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). This makes it possible to serialize weak models, i.e. 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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top