Polymorphism with Serialized Data

谁都会走 提交于 2019-12-11 19:16:37

问题


I am trying to use Polymorphism with data that is to be serialized and deserialized. However, it seems that the polymorphic properties are being lost on serialization:

// 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

How can you properly serialize these classes in this case?

来源:https://stackoverflow.com/questions/10362513/polymorphism-with-serialized-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!