我一直在阅读周围的内容,但我还没有找到解决我的问题的方法
我目前正在使用一个业务对象来保存我的所有数据,我们需要将该对象与 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/