2015-12-21 31 views
2

我經常發現自己實現這種類:是否有一個優雅的序列化模式?

public class Something 
{ 
    public string Serialize() 
    { 
     // serialization code goes here 
    } 

    public static Something Deserialize(string str) 
    { 
     // deserialization code goes here 
    } 
} 

我想通過使上面的類實現一個看起來像這樣的接口來執行這項過這個類型的所有類:

public interface ISerializationItem<T> 
{ 
    string Serialize(); 
    T Deserialize(string str); 
} 

唉,這是不可能的,因爲接口不能覆蓋靜態方法,並且該方法需要是靜態的,以便它不依賴於類的任何實例。

更新:通常,我會反序列化,如下所示;靜態方法有效地用於構造類的一個實例,所以我不希望已經在手的情況下才能夠做到這一點:

var str = "Whatever"; 
var something = Something.Deserialize(str); 

有沒有強制執行這個約束有道?

+0

這取決於系列化的*類型*您在做什麼。你執行什麼類型的序列化? JSON? XML?二進制? –

+2

'方法需要是靜態的,所以它不依賴於類的任何實例。「你能解釋這部分嗎? –

+0

我同意哈姆雷特,我不明白爲什麼該方法需要靜態。我不使用靜態方法進行序列化。 –

回答

1

保持您的「數據」類簡單/純粹的任何邏輯,然後將序列化過程寫入單獨的類。這將使維護數據類和序列化器變得更容易。如果每個類都需要定製,那麼創建屬性類並用這些屬性修飾你的數據類。

下面是一些僞例子...

public class Employee 
{ 
    public int Id { get; set;} 

    [ForceSpecialHandling] 
    public string Name { get; set; } 
} 

public class CustomSerializer 
{ 
    public T Serialize<T>(string data) 
    { 
      // Write the serialization code here. 
    } 
} 

// This can be whatever attribute name you want. 
// You can then check if the property or class has this attribute using reflection. 
public class ForceSpecialHandlingAttribute : Attribute 
{ 
} 
相關問題