Is it possible to serialize a list of System.Object objects using protocol buffers

后端 未结 1 339
孤城傲影
孤城傲影 2021-01-14 03:46

I have a list of objects of various data types (DateTime, int, decimal, string).

List myObjects = new List();
myObjects.Add(3);
         


        
      
      
      
1条回答
  •  说谎
    说谎 (楼主)
    2021-01-14 04:42

    Check these to see why this is a way to go:

    1. The need for a parameterless constructor

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

    3. why DynamicType=true wouldn't have worked

    4. the need for an abstract base class and concrete implementations, by the creator of protobuf-net

    5. why no serializer for object

    Abstract base

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

    Implementation

        [ProtoContract()]
        class ObjectWrapper : 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; }
        }
    

    Test

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

    0 讨论(0)
提交回复
热议问题