1

我有一个包含接口成员变量的类。我如何反序列化这个类

interface ISensor { }

[Serializable]
class Sensor: ISensor { }

[Serializable]
class Root
{
    [XmlElement("Sensor")]
    public List<ISensor> SensorList{ get; set; }
}

我的 XML 将是这样的

  <?xml version="1.0" encoding="us-ascii"?>
<Root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <Sensor >
        <SensorName>Name1</SensorName>
        <SensorValue>0.0</SensorValue>
    </Sensor>
    <Sensor>
        <SensorName>Name2</SensorName>
        <SensorValue>148.00</SensorValue>
    </Sensor>
</Root>
4

1 回答 1

1

假设您使用XmlSerializer的是 ,序列化和反序列化都需要进行两项更改:

  1. 告诉序列化器可以出现的类型列表,也就是继承自的类型Sensor
  2. 对 List 使用类而不是接口,换句话说,替换List<ISensor>List<Sensor>.

不幸的是,XmlSerializer 不能以您想要的方式处理接口。有关详细信息,请参阅XmlSerializer 序列化通用接口列表

如果使用基类不是一个选项,您可以通过实现来编写自己的 XML 序列化程序IXmlSerializable。手动覆盖ReadXml并解析 XML。

例如:

public interface ISensor { }

[Serializable]
public class Sensor : ISensor { }

[Serializable]
public class Root
{
    // Changed List<ISensor> to List<Sensor>. I also changed
    // XmlElement to XmlArray so it would appear around the list.       
    [XmlArray("Sensor")]
    public List<Sensor> SensorList { get; set; }
}

[Serializable]
public class SensorA : Sensor
{
    [XmlElement("A")]
    public string A { get; set; }
}

[Serializable]
public class SensorB : Sensor
{
    [XmlElement("B")]
    public string B { get; set; }
}

class Program
{
    public static void Main(string[] args)
    {
        XmlSerializer xmlSerializer;

        Root root = new Root();
        root.SensorList = new List<Sensor>();
        root.SensorList.Add(new SensorA() {A = "foo"});
        root.SensorList.Add(new SensorB() {B = "bar"});

        // Tell the serializer about derived types
        xmlSerializer = new XmlSerializer(typeof (Root), 
            new Type[]{typeof (SensorA), typeof(SensorB)});
        StringBuilder stringBuilder = new StringBuilder();
        using (StringWriter stringWriter = new StringWriter(stringBuilder))
        {
            xmlSerializer.Serialize(stringWriter, root);
        }

        // Output the serialized XML
        Console.WriteLine(stringBuilder.ToString());

        Root root2;
        using (StringReader stringReader = new StringReader(stringBuilder.ToString()))
        {
            root2 = (Root) xmlSerializer.Deserialize(stringReader);
        }
    }
}

Console.WriteLine 语句的输出是:

<?xml version="1.0" encoding="utf-16"?>
<Root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Sensor>
    <Sensor xsi:type="SensorA">
      <A>foo</A>
    </Sensor>
    <Sensor xsi:type="SensorB">
      <B>bar</B>
    </Sensor>
  </Sensor>
</Root>
于 2013-01-01T07:50:39.533 回答