Protobuf-net: Serializing a 3rd party class with a Stream data member

前端 未结 2 1126
孤独总比滥情好
孤独总比滥情好 2021-01-23 01:54

How do you serialize a Stream (or more correctly Stream derived) data member of a class?

Assuming we have a 3rd Party class that we can\'t attribute:

pub         


        
2条回答
  •  北恋
    北恋 (楼主)
    2021-01-23 02:09

    Stream is a very complex beast, and there is no inbuilt serialization mechanism for that. Your code configures it as though it were a type with no interesting members, which is why it is coming back as empty.

    For this scenario, I'd probably create a surrogate, and set it up with just:

    RuntimeTypeModel.Default.Add(typeof(Fubar), false)
           .SetSurrogate(typeof(FubarSurrogate));
    

    where:

    [ProtoContract]
    public class FubarSurrogate
    {
        [ProtoMember(1)]
        public string Label { get; set; }
        [ProtoMember(2)]
        public int DataType { get; set; }
        [ProtoMember(3)]
        public byte[] Data { get; set; }
    
        public static explicit operator Fubar(FubarSurrogate value)
        {
            if(value == null) return null;
            return new Fubar {
                Label = value.Label,
                DataType = value.DataType,
                Data = value.Data == null ? null : new MemoryStream(value.Data)
            };
        }
        public static explicit operator FubarSurrogate(Fubar value)
        {
            if (value == null) return null;
            return new FubarSurrogate
            {
                Label = value.Label,
                DataType = value.DataType,
                Data = value.Data == null ?
                     null : ((MemoryStream)value.Data).ToArray()
            };
        }
    }
    

提交回复
热议问题