繁体   English   中英

序列化具有接口的对象

[英]Serialize an object that has an interface

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

接口 TypeEntre 也有 [Serializable] 属性,还有我的每个使用这个接口的类的 [XmlInclude (typeof (Mouse)]。

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

另外,我应该如何解决这个问题?

另外,这里是我发现的序列化/反序列化方法,在没有接口的情况下似乎效果很好: https : //stackoverflow.com/a/22417240/6303528

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

我的接口 TypeEntre 变成了一个抽象类。

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

此外,Mouse 类有一个不可序列化的 IntPtr。 我不得不将其转换为 Int64(长)。 来源来自@dbc 评论和此处: 使用 XmlSerializer 序列化 IntPtr

最后,元组不能被序列化,因为它没有无参数的构造函数。 对此的解决方法是将元组的类型更改为我按照此示例创建的类 (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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM