【问题标题】:Serialize an object that has an interface序列化具有接口的对象
【发布时间】: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

【问题讨论】:

标签: c# xml interface xml-serialization xmlserializer


【解决方案1】:

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

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

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-11
    • 2011-05-02
    相关资源
    最近更新 更多