protobuf-net Serializing System.Object With DynamicType Throws Exception

自作多情 提交于 2019-12-19 21:51:33

问题


In my application, I'm serializing messages to send over the wire using protobuf-net. Each message has a list of key-value pairs for header information.

However, I'm running into an exception and I've been able to reproduce it with a very simplified example:

[TestFixture]
public class SerializationTests
{
    [ProtoContract]
    public class MyType
    {
        [ProtoMember(1, DynamicType = true)]
        public object Property { get; set; }
    }

    [Test]
    public void SerializationTest()
    {
        var myType = new MyType {Property = DateTime.UtcNow.ToBinary()};
        Action action = () => myType.Serialize();
        action.ShouldNotThrow();
    }
}

public static byte[] Serialize<T>(this T itemToSerialize)
{
    using (MemoryStream ms = new MemoryStream())
    {
        ProtoBuf.Serializer.Serialize(ms, itemToSerialize);
        byte[] objectArray = ms.ToArray();
        return objectArray;
    }
}

This test currently fails with the exception: System.InvalidOperationException: "Dynamic type is not a contract-type: Int64".

The property is of type object so I can put various data in there - since this is header information. I'm trying to avoid having multiple header lists where each one is strongly typed.

If I change Property to be of type long, then the test works. If I remove the DynamicType=true, then I get an exception indicating that no serializer exists for type object.

Since the test works when I change the type of Property, that seems to imply that DynamicType and long's don't work together.

I'm currently using r640 (I believe that's the latest on NuGet).


回答1:


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



来源:https://stackoverflow.com/questions/17192702/protobuf-net-serializing-system-object-with-dynamictype-throws-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!