我正在尝试将多态性与要序列化和反序列化的数据一起使用。但是,似乎多态属性在序列化时丢失了:
// Serialize
[System.Serializable]
public ParentClass()
{
public string someString = "a string";
}
[System.Serializable]
public ChildClass() : ParentClass
{
public int someInt;
public ChildClass(int _someInt)
{
someInt = _someInt;
}
}
List<ParentClass> list = new List<ParentClass>();
list.Add(new ChildClass(5));
// Data is serialized
// Data is deserialized
Debug.Log(list[0].someString);
// Output: a string; Works as intended
Debug.Log((list[0] as ChildClass).someInt));
// Null Reference Exception
在这种情况下,如何正确序列化这些类?