是否可以使用协议缓冲区序列化System.Object对象列表

时间:2016-08-11 20:19:19

标签: c# serialization .net-4.5 protocol-buffers protobuf-net

我有各种数据类型的对象列表(DateTime,int,decimal,string)。

List<object> myObjects = new List<object>();
myObjects.Add(3);
myObjects.Add(3.9m);
myObjects.Add(DateTime.Now);
myObjects.Add("HELLO");

我能够使用protobuf-net序列化此列表,但反序列化总是抛出异常:&#34;附加信息:不期望类型,也不能推断出合同:System.Object&#34;。

using (var ms = new MemoryStream())
{
    Serializer.Serialize(ms, list2);
    var bytes = ms.ToArray();
    ms.Position = 0;
    var clone = Serializer.Deserialize(typeof(List<object>), ms); //Throws exception
}

我没有任何明确的合同,我想这是问题所在?但是,我确实知道序列化对象的预期类型是什么,但我如何告诉protobuf-net?

1 个答案:

答案 0 :(得分:3)

检查这些以了解为什么这是一种方法:

  1. The need for a parameterless constructor

  2. why dynamic instead of object wouldn't have worked

  3. 为什么DynamicType=true wouldn't have worked

  4. the need for an abstract base class and concrete implementations,由protobuf-net的创建者

  5. why no serializer for object

  6. 抽象基础

        [ProtoContract]
        [ProtoInclude (1, typeof(ObjectWrapper<int>))]
        [ProtoInclude(2, typeof(ObjectWrapper<decimal>))]
        [ProtoInclude(3, typeof(ObjectWrapper<DateTime>))]
        [ProtoInclude(4, typeof(ObjectWrapper<string>))]
        abstract class ObjectWrapper {
            protected ObjectWrapper() {}
            abstract public object ObjectValue { get; set; }
        }
    

    实施

        [ProtoContract()]
        class ObjectWrapper<T> : ObjectWrapper
        {
            public ObjectWrapper(): base() { }
            public ObjectWrapper(T t) { this.Value = t; }
    
            [ProtoIgnore()]
            public override object ObjectValue
            {
                get { return Value; }
                set { Value = (T)value; }
            }
    
            [ProtoMember(1)]
            public T Value { get; set; }
        }
    

    测试

            var myObjects = new List<ObjectWrapper>();
            myObjects.Add(new ObjectWrapper<int>(3));
            myObjects.Add(new ObjectWrapper<decimal>(3.9m));
            myObjects.Add(new ObjectWrapper<DateTime> (DateTime.Now));
            myObjects.Add(new ObjectWrapper<string> ("HELLO"));
            var clone = Serializer.DeepClone(myObjects);