c# - 序列化列表持有 XML 接口(interface)

标签 c# xml serialization

我一直在阅读周围的内容,但我还没有找到解决我的问题的方法

我目前正在使用一个业务对象来保存我的所有数据,我们需要将该对象与 XML 相互转换。

我的对象包含一个操作列表(列表...),但有 2 种操作类型(目前)。 我必须有操作类型 SimpleAction 和 CompositeAction,它们都继承自 IAction,允许它们都保存在操作列表中。

现在您可能会看到问题,因为接口(interface)无法序列化,因为它们不包含数据。

如何使用一些示例代码编写一个类或序列化器来获取该对象类型并执行,然后使用正确的类型序列化对象?

一些代码:

  [XmlArray("Actions")]
  public List<IAction> Actions { get; set; }

  public interface IAction
   {
     int ID { get; set; }

     ParameterCollection Parameters { get; set; }

     List<SectionEntity> Validation { get; set; }

     TestResultEntity Result { get; set; }

     string Exception { get; set; }
   }

[XmlType("A")]
public class SimpleActionEntity : IAction
{
    #region IAction Members

    [XmlAttribute("ID")]
    public int ID { get; set; }

    [XmlIgnore]
    public ParameterCollection Parameters { get; set; }

    [XmlIgnore]
    public List<SectionEntity> Validation { get; set; }

    [XmlIgnore]
    public TestResultEntity Result { get; set; }

    [XmlElement("Exception")]
    public string Exception { get; set; }

    #endregion
}

任何帮助将不胜感激。 :)

最佳答案

您可以使用 XmlArrayItemAttribute,正如我们所讨论的,创建 IAction 列表是不好的,因此最好创建基类

public interface IAction {}
public abstract class ActionBase : IAction {}
public class SimpleAction : ActionBase {}
public class ComplexAction : ActionBase {}


[XmlArray("Actions")]
[XmlArrayItem(typeof(SimpleAction)),XmlArrayItem(typeof(ComplexAction))]
public List<ActionBase> Actions { get; set; }

事实上,您还可以像这样控制 xml 文件中的元素名称:

  [XmlArray("Actions")]
  [XmlArrayItem(typeof(SimpleAction),ElementName = "A")]
  [XmlArrayItem(typeof(ComplexAction),ElementName = "B")]
  public List<ActionBase> Actions { get; set; }

关于c# - 序列化列表持有 XML 接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1131689/

相关文章:

java - Java/Scala 是否有 Colander/DictShield 的等价物?

c# - 为什么在 WCF 反序列化程序初始化对象时不调用抽象基类的构造函数?

c# - 尝试将文件保存到目录时出现访问被拒绝错误

c# - session 状态 MVC3

php - 从 XML 流生成 CSV 文件以进行 MYSQL 导入

java - 将节点转换为元素时出现 Dom XML 解析器异常

java - GWT RPC 未生成正确的 gwt.rpc 文件

c# - 配置错误 - 调用目标已引发异常

c# - C#-UrlHistoryWrapper类-没有足够的存储空间来处理此命令。 (来自HRESULT : 0x80070008)的异常

java - 使用VTD-XML仅修改元素文本