序列化具有接口

时间:2016-05-07 10:26:26

标签: c# xml interface xml-serialization xmlserializer

我的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 ...
}

TypeEntree是一个空接口,它只能关联不同的对象并在我的应用程序中轻松使用它们。例如,以下是使用此接口的两个对象:

[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)]。

这是我的问题:为什么当我尝试序列化时,它无法检测到我的对象的类型(任务中的typeEntree),因为我添加了[XmlInclude(typeof(Mouse)]属性?

此外,我该如何解决此问题?

另外,以下是序列化/反序列化的方法我发现没有接口似乎工作得很好:https://stackoverflow.com/a/22417240/6303528

1 个答案:

答案 0 :(得分:1)

感谢我在第一个问题的评论中的@dbc链接,我能够找出每个问题。这是我做的:

我的界面TypeEntree成了一个抽象类。

[Serializable]
[XmlInclude(typeof(Mouse))]
[XmlInclude(typeof(Keyboard))]
[XmlInclude(typeof(Sequence))]
public abstract class TypeEntree
{
}

此外,Mouse类有一个IntPtr,它不可序列化。我不得不将它转换为Int64(很长)。来自@dbc评论和来源:Serialize an IntPtr using XmlSerializer

最后,由于没有无参数构造函数,因此无法序列化元组。解决这个问题的方法就是按照以下示例将Tuple的类型更改为我创建的类(TupleModifier):https://stackoverflow.com/a/13739409/6303528

public class TupleModifier<T1, T2, T3, T4>
{
    public T1 Item1 { get; set; }
    public T2 Item2 { get; set; }
    public T3 Item3 { get; set; }
    public T4 Item4 { get; set; }

    public TupleModifier() { }

    public static implicit operator TupleModifier<T1, T2, T3, T4>(Tuple<T1, T2, T3, T4> t)
    {
        return new TupleModifier<T1, T2, T3, T4>()
        {
            Item1 = t.Item1,
            Item2 = t.Item2,
            Item3 = t.Item3,
            Item4 = t.Item4
        };
    }

    public static implicit operator Tuple<T1, T2, T3, T4>(TupleModifier<T1, T2, T3, T4> t)
    {
        return Tuple.Create(t.Item1, t.Item2, t.Item3, t.Item4);
    }
}

并在Sequence类中使用它,就像使用它一样:

public List<TupleModifier<string, Point, long, long>> actions;
相关问题