恢复继承类型之间的公共变量

时间:2018-11-18 20:25:24

标签: c# reflection

我有两个类:GameObjectSampleObject : GameObject以及类型为GameObject的列表。我已经将这些类的实例序列化为XML文档。一旦我反序列化(加载)此文档,就会出现我的问题。

在XML文件中,实例序列化为:

<Root>
 <GameObject>
  <Type>Namespace.MyType</Type>
 </GameObject>
</Root>

类型代表所需的类型。每个实例都在 GameObject 标签下进行序列化。

解析此文档后,我获得了GameObject的列表。现在我需要恢复正确的类型:

foreach (GameObject g in myList)
{
  GameObject tempObject = (GameObject)Activator.CreateInstance(Type.GetType(g.TypeString));              
}

问题是tempObject为空白(正确)。我想(用一些速记)恢复gtempObject之间的公共(共享)变量。例如:

tempObject.Property1 = g.Property1
tempObject.Property2 = g.Property2

1 个答案:

答案 0 :(得分:1)

XmlSerializer支持多态,但是您必须预先指出要扩展的类型。您可以使用基本类型上的属性来执行此操作:

[XmlInclude(typeof(SampleObject))]
public class GameObject
{
}

例如,如果您不拥有XmlSerializer类,也可以将这些类型传递给GameObject的构造函数。完整示例:

Root root = new Root();
root.Objects.Add(new GameObject { Property1 = 2 });
root.Objects.Add(new SampleObject { Property1 = 5, Property2 = 12 });

XmlSerializer ser = new XmlSerializer(typeof(Root), new Type[] { typeof(SampleObject) });
using (MemoryStream stream = new MemoryStream())
{
    ser.Serialize(stream, root);
    stream.Position = 0;
    Root deserialized = (Root)ser.Deserialize(stream);
}

它输出以下xml:

<?xml version="1.0"?>
<Root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <GameObject>
    <Property1>2</Property1>
  </GameObject>
  <GameObject xsi:type="SampleObject">
    <Property1>5</Property1>
    <Property2>12</Property2>
  </GameObject>
</Root>

在此示例中,我使用了以下类:

[XmlRoot]
public class Root
{
    public Root()
    {
        Objects = new List<GameObject>();
    }

    [XmlElement("GameObject")]
    public List<GameObject> Objects { get; set; }
}

public class GameObject
{
    public int Property1 { get; set; }
}

public class SampleObject : GameObject
{
    public int Property2 { get; set; }
}