在protobuf-net中使用Surrogates无法解决空列表和空列表之间的区别

时间:2011-07-13 07:20:49

标签: c# protobuf-net

protobuf没有内置支持空列表和空列表之间的差异。 但是,我们的业务对象确实不同,因为null表示列表尚未从数据库中提取,而空表示没有找到任何项目。

所以我试图在protobuf-net中使用Surrogates克服这个限制。然而,问题是,我的代理人根本没有被调用。

这是我正在做的事情:

//DataContracts
    [ProtoContract]
    public class SerializeClassCollectionContainer
    {
        [ProtoMember(1, AsReference=true)]
        public SerializeClassCollection Collection { get; set; }
    }

    [ProtoContract]
    public class SerializeClassCollection : List<SerializeClass>
    {
    }

[ProtoContract]
        public class SerializeClassCollectionSurrogate
        {
            [ProtoMember(1)]
            public bool IsEmpty { get; set; }

            [ProtoMember(2, AsReference = true)]
            public List<SerializeClass> Elements { get; set; }

            public static implicit operator SerializeClassCollection(SerializeClassCollectionSurrogate surrogate)
            {
                if (surrogate == null)
                    return null;

                if (surrogate.Elements != null)
                {
                    var col = new SerializeClassCollection();
                    col.AddRange(surrogate.Elements);
                    return col;
                }

                if (surrogate.IsEmpty)
                {
                    return new SerializeClassCollection();
                }

                return null;
            }

            public static implicit operator SerializeClassCollectionSurrogate(SerializeClassCollection collection)
            {
                if (collection == null)
                    return null;

                var surrogate = new SerializeClassCollectionSurrogate();
                surrogate.IsEmpty = collection.Count == 0;
                surrogate.Elements = collection.ToList();

                return surrogate;
            }
        }

//Evaluation
RuntimeTypeModel.Default[typeof(SerializeClassCollection)].SetSurrogate(typeof(Surrogates.SerializeClassCollectionSurrogate));

SerializeClassCollectionContainer serializeClassCollectionContainer = GetCustomObject();
            serializeClassCollectionContainer.Collection = new SerializeClassCollection(); //empty collection

            using (var writer = new StreamWriter(OutputDir + "proto.bin"))
            {
                Serializer.Serialize(writer.BaseStream, serializeClassCollectionContainer);
            }

            using(var reader = new StreamReader(OutputDir + "proto.bin"))
            {
                var deserialized = Serializer.Deserialize<SerializeClassCollectionContainer>(reader.BaseStream);
                if(deserialized.Collection == null)
                    throw new InvalidOperationException("Surrogate does not work");
            }

我做错了吗? 或者这是一个功能,不应该工作? 或者它应该工作但是一个错误?

我尝试使用protobuf-net trunk修订版433。

此致 TH

0 个答案:

没有答案