protobuf-net自定义序列化和模型配置
本文关键字:模型 配置 序列化 自定义 protobuf-net | 更新日期: 2023-09-27 18:25:24
所以我正在为Unity3D编写一个自定义序列化系统,让用户实现和选择不同的序列化。我目前支持BinaryFormatter
和protobuf-net
。然而在这个系统中,我有用于序列化的持久自定义规则,我希望我的序列化程序能够很好地使用这些规则:
- 只有使用
[Serializable]
对类型进行注释时,类型才是可序列化的 - 带有副作用的属性没有序列化,只有自动作用
- 公共字段/自动属性隐式序列化
- 非公共字段/自动属性只有在应用了自定义属性时才会序列化(我有很多:
[Save]
、[Serialize]
和[SerializeField]
现在我想调整我的protobuf网络模型以适应这些规则,这样我就不必使用任何protobuf自定义属性,如ProtoContract
、ProtoMember
等。
我认为我可以做到这一点的方法是,拥有一个可序列化类型的数组,用户可以将他的自定义类型添加到其中(这样他就不需要对这些类型使用ProtoContract)——我会迭代这些类型,并将它们添加到我的模型中。对于每种类型,我都会获得满足序列化规则的成员,并将它们添加到模型中。
我想说的另一件事是,假设你有一个抽象类A
,它有孩子B
和C
,用户不必显式地添加B
和C
,他们只添加A
,我会得到A
的孩子,然后自己添加。
我的问题归结为:用户不必写这个:
[ProtoContract]
[ProtoInclude(1, typeof(Child1))]
[ProtoInclude(2, typeof(Child2))]
public abstract class AbstractBase
{
public abstract int Num { get; set; }
}
[ProtoContract]
public class Child1 : AbstractBase
{
[ProtoMember(1)]
public int x;
public override int Num { get { return x; } set { x = value; } }
}
[ProtoContract]
public class Child2 : AbstractBase
{
[ProtoMember(1)]
public int y;
[ProtoMember(2)]
public int z;
public override int Num { get { return y; } set { y = value; } }
}
我希望他们能够写下:
[Serializble]
public abstract class AbstractBase
{
public abstract int Num { get; set; }
}
[Serializble]
public class Child1 : AbstractBase
{
public int x;
public override int Num { get { return x; } set { x = value; } }
}
[Serializble]
public class Child2 : AbstractBase
{
public int y;
public int z;
public override int Num { get { return y; } set { y = value; } }
}
// ProtobufSerializableTypes.cs
public static Type[] SerializableTypes = new[]
{
typeof(AbstractBase)
};
以下是我尝试过的:
[TestClass]
public class ProtobufDynamicSerializationTestSuite
{
private AbstractBase Base { get; set; }
private Type[] SerializableTypes { get; set; }
[TestInitialize]
public void Setup()
{
Base = new Child1();
SerializableTypes = new[]
{
typeof(AbstractBase)
};
}
[TestMethod]
public void ShouldCopyWithCustomConfig()
{
var model = TypeModel.Create();
Func<Type, MetaType> addType = type =>
{
log("adding type: {0}", type.Name);
return model.Add(type, false);
};
var hierarchy = new Dictionary<MetaType, List<Type>>();
for (int i = 0; i < SerializableTypes.Length; i++)
{
var type = SerializableTypes[i];
var meta = addType(type);
var temp = new List<Type>();
var children = type.Assembly.GetTypes().Where(t => t.IsSubclassOf(type) && !t.IsAbstract).ToList();
for(int j = 0; j < children.Count; j++)
{
var child = children[j];
addType(child);
log("adding subtype {0} with id {1}", child.Name, j + 1);
meta.AddSubType(j + 1, child);
temp.Add(child);
}
hierarchy[meta] = temp;
}
Func<Type, string[]> getMemberNames = x =>
//SerializationLogic.GetSerializableMembers(x, null) // real logic
x.GetMembers(BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Public) // dummy logic
.Where(m => m.MemberType == MemberTypes.Field)
.Select(m => m.Name)
.ToArray();
foreach (var entry in hierarchy)
{
int id = 1;
foreach (var type in entry.Value)
{
foreach (var member in getMemberNames(type))
{
log("adding member {0} to type {1} with id {2}", member, type.Name, id);
entry.Key.Add(id++, member);
}
}
}
Base.Num = 10;
var copy = (AbstractBase)model.DeepClone(Base);
Assert.AreEqual(copy.Num, 10);
}
void log(string msg, params object[] args)
{
Console.WriteLine(string.Format(msg, args));
}
void log(string msg)
{
log(msg, new object[0]);
}
}
因此,我的尝试是将所有必要的类型添加到模型中,将所有子类型添加到父类型中,然后对所有添加的类型进行迭代,并从该类型向模型中添加适当的字段/属性(对应于我的序列化规则)
然而,这未能:
Test Name: ShouldCopyWithCustomConfig
Test Outcome: Failed
Result Message:
Test method ProtobufTests.ProtobufDynamicSerializationTestSuite.ShouldCopyWithCustomConfig threw exception:
System.ArgumentException: Unable to determine member: x
Parameter name: memberName
Result StandardOutput:
adding type: AbstractBase
adding type: Child1
adding subtype Child1 with id 1
adding type: Child2
adding subtype Child2 with id 2
adding member x to type Child1 with id 1
我做错了什么?还有更好的方法吗?
谢谢!
注意,最初我没有这个字典步骤,我试图在将一个类型添加到模型中后立即添加它的成员,但这失败了,如果我必须说,类型A
和B
,A
有一个B
引用,如果我试图添加类型A
及其成员,我会出现B
,protobuf在现阶段无法识别,因为它还没有添加到模型。。。所以我认为有必要先添加类型,然后添加它们的成员。。。
主要问题似乎是entry.Key
引用了基类型,但您试图描述特定子类型的成员;我是这么做的:
foreach (var entry in hierarchy)
{
foreach (var type in entry.Value)
{
var meta = model.Add(type, false);
var members = getMemberNames(type);
log("adding members {0} to type {1}",
string.Join(",", members), type.Name);
meta.Add(getMemberNames(type));
}
}
我还添加了一些严格的订购:
.OrderBy(m => m.Name) // in getMemberNames
和
.OrderBy(x => x.FullName) // in var children =
以确保id至少是可预测的。请注意,在protobuf中,id非常重要:没有严格定义id的结果是,如果有人将AardvarkCount
添加到您的模型中,它可能会偏移所有id,并破坏现有数据的反序列化。需要注意的事情。