protobuf 没有内置支持区分空列表和空列表。
但是,我们的业务对象确实有所不同,因为 null 表示尚未从数据库中提取列表,而empty 表示未找到任何项目。
所以我试图在 protobuf-net 中使用代理来克服这个限制。然而问题是,我的代理人根本没有被召唤。
这是我正在做的事情:
//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 主干的修订版 433 进行此操作。
问候,
TH
None
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)