2016-05-07 43 views
1

我遇到了與我的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運算(鼠標)]我的每個類使用該。接口

這裏是我的問題:爲什麼當我試圖序列,它無法檢測到我的對象的類型(在任務typeEntree),因爲我加入了[XmlInclude(typeof運算(鼠標)屬性

另外,我該如何解決這個問題?

Additionnally,這裏有串行/解串的方法,我發現,似乎工作得非常好無接口:https://stackoverflow.com/a/22417240/6303528

+0

你使用哪個序列化程序? – rene

+0

在最後一句中,我指定了它。 http://stackoverflow.com/a/22417240/6303528 - XML XmlSerializer –

+0

序列化程序添加不用於序列化的屬性,但會反序列化。網絡庫在反序列化時需要屬性來區分繼承的類。 – jdweng

回答

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

最後,一個元組不能被序列化,因爲它沒有無參數的構造函數。一個修復到這是簡單地改變元組的類型以下這個例子中我創建的類(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); 
    } 
} 

和在序列類使用它像它被用來:

public List<TupleModifier<string, Point, long, long>> actions; 
相關問題