【发布时间】:2016-05-07 10:26:25
【问题描述】:
我的 XML 序列化问题非常有问题。我一直在研究我的项目,以(de)序列化一个具有接口作为属性的对象。我知道你不能序列化一个接口,这就是我的错误告诉我的。
这是我要保存到文件的对象的示例:
public class Task
{
public int id;
public string name;
public TypeEntree typeEntree;
public int idRequired;
public string code;
public int waitTime;
public string nameApp;
// ... Constructors (empty and non-empty) and methods ...
}
TypeEntre 是一个空接口,它只是关联不同的对象并在我的应用程序中轻松使用它们。例如,这里有两个使用这个接口的对象:
[Serializable]
public class Mouse : TypeEntree
{
public Point point;
public IntPtr gaucheOuDroite;
public string image;
// ... Constructors (empty and non-empty) and methods ...
}
[Serializable]
public class Sequence : TypeEntree
{
public List<Tuple<string, Point, long, IntPtr>> actions;
// ... Constructors (empty and non-empty) and methods ...
}
接口 TypeEntree 还具有 [Serializable] 属性以及使用此接口的每个类的 [XmlInclude (typeof (Mouse)]。
这是我的问题:为什么当我尝试序列化时,由于我添加了 [XmlInclude (typeof (Mouse)] 属性,它无法检测到我的对象的类型(Task 中的 typeEntre)?
另外,我应该如何解决这个问题?
此外,我发现以下是序列化/反序列化的方法,在没有接口的情况下似乎效果很好:https://stackoverflow.com/a/22417240/6303528
【问题讨论】:
-
您使用哪个序列化程序?
-
在最后一句中我指定了它。 stackoverflow.com/a/22417240/6303528 - XML XmlSerializer
-
序列化器添加的属性不是序列化,而是反序列化。 net库在反序列化时需要属性来区分继承的类。
-
即使添加了
XmlInclude,也不能用XmlSerializer序列化接口。请参阅XML serialization of interface property 或Serializing interfaces。XmlInclude用于基类/派生类层次结构。 -
顺便说一句,如果我将
TypeEntree更改为public abstract class,您的类型仍然无法序列化,因为IntPtr无法直接序列化。作为一种解决方法,您可以使用long代理属性。见Serialize an IntPtr using XmlSerializer。
标签: c# xml interface xml-serialization xmlserializer