我使用代理人,我想在序列化过程中执行检查以跳过错误的项目,但是我找不到办法去做任何想法?
在创建代理项后调用BeforeSerialize 方法,我想知道如何跳过没有在protoBuf序列化上下文中指定的要求的项目。
下面是重现我的场景的示例代码。
public class Person
{
public Person(string name, GenderType gender)
{
Name = name;
Gender = gender;
}
public string Name { get; set; }
public GenderType Gender { get; set; }
}
public class PersonSurrogate
{
public string Name { get; set; }
public byte Gender { get; set; }
public PersonSurrogate(string name, byte gender)
{
Name = name;
Gender = gender;
}
protected virtual bool CheckSurrogateData(GenderType gender)
{
return gender == GenderType.Both || (GenderType)Gender == gender;
}
#region Static Methods
public static implicit operator Person(PersonSurrogate surrogate)
{
if (surrogate == null) return null;
return new Person(surrogate.Name, (GenderType)surrogate.Gender);
}
public static implicit operator PersonSurrogate(Person source)
{
return source == null ? null : new PersonSurrogate(source.Name, (byte)source.Gender);
}
#endregion
protected virtual void BeforeSerialize(ProtoBuf.SerializationContext serializationContext)
{
var serializer = serializationContext.Context as FamilySerializer;
if (serializer == null)
throw new ArgumentException("Serialization context does not contain a valid Serializer object.");
if (!CheckSurrogateData(serializer.GenderToInclude))
{
// ** How can I exclude this item from the serialization ? **//
}
}
}
[Flags]
public enum GenderType : byte
{
Male = 1,
Female = 2,
Both = Male | Female
}
/// <summary>
/// Class with model for protobuf serialization
/// </summary>
public class FamilySerializer
{
public GenderType GenderToInclude;
public RuntimeTypeModel Model { get; protected set; }
protected virtual void FillModel()
{
Model = RuntimeTypeModel.Create();
Model.Add(typeof(Family), false)
.SetSurrogate(typeof(FamilySurrogate));
Model[typeof(FamilySurrogate)]
.Add(1, "People") // This is a list of Person of course
.UseConstructor = false;
Model.Add(typeof(Person), false)
.SetSurrogate(typeof(PersonSurrogate));
MetaType mt = Model[typeof(PersonSurrogate)]
.Add(1, "Name")
.Add(2, "Gender");
mt.SetCallbacks("BeforeSerialize", null, null, null); // I'd like to check surrogate data and skip some items - how can I do?
mt.UseConstructor = false; // Avoids to use the parameterless constructor.
}
}
答案 0 :(得分:1)
您所描述的并不是序列化程序当前尝试定位的场景。基于每个属性/字段支持的条件序列化,但不支持每个对象。
但是仍然有可能让它工作 - 但这取决于上下文是什么,即在模型中有<{1}}对象是什么?你能改变那种模式吗? (可能不是,因为你正在使用代理人)。
我的默认答案是,只要事情停止工作,就是说:为序列化工作创建一个单独的DTO模型,并使用您要序列化的数据填充 - 而不是努力使您的常规域模型能够很好地满足复杂的序列化要求。