2011-11-21 68 views
1

可以說,我有一個類中有對象。從MemoryStream反序列化()

namespace Class_Serialization 
{ 
    [Serializable] 
    public class Data 
    { 
     public string Name = "Example1"; 
     public string place = "Torino"; 
     public DateTime time = DateTime.Now; 
    } 
} 

我試圖用ISerialization接口

[Serializable] 
public class SerializeThisClass : ISerializable 
{ 
    public Data StreamThisData; 

    public SerializeThisClass() 
    { 

    } 

    public SerializeThisClass(Data _StreamThisData) 
    { 
     StreamThisData = _StreamThisData; 
    } 
    [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)] 
    void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) 
    { 
     info.AddValue("Object Data", StreamThisData); 
    } 
} 

我們序列化,當我用下面

Data DataToSerialize = new Data(); 
BinaryFormatter DataToBinary = new BinaryFormatter(); 
SerializeThisClass serialize = new SerializeThisClass(DataToSerialize); 
SerializeIn SerializeInMem = new SerializeIn(); 
DataToBinary.Serialize(SerializeInMem.StreamOfData, serialize); 
ListOfStreams.Add(SerializeInMem); 

它通常序列化的代碼序列化,但是當我嘗試反序列化,它給我錯誤

BinaryFormatter BinaryToData = new BinaryFormatter(); 
foreach (SerializeIn x in ListOfStreams) 
{ 
    x.StreamOfData.Position = 0; 
    SerializeThisClass DeserializeData = (SerializeThisClass)BinaryToData.Deserialize(x.StreamOfData); 
    MessageBox.Show("Name: " + DeserializeData.StreamThisData.Name + "\nPlace: " + DeserializeData.StreamThisData.place + "\nDateTime: " + DeserializeData.StreamThisData.time.ToString()); 
} 

Error: $exception{"The constructor to deserialize an object of type 'Class_Serialization.SerializeThisClass' was not found."} System.Exception {System.Runtime.Serialization.SerializationException}

+0

嘗試做這種方式http://stackoverflow.com/questions/5017274/c-sharp-binaryformatter-and-deserialization-complex-objects –

+0

坦率地說,因爲所有你正在做的是添加一個單一的元素,我會試圖刪除'ISerializable'並讓'BinaryFormatter'自動處理它。 –

回答

4

如果要實現ISerializable,你需要簽名的構造方法:

protected YourType(SerializationInfo information, StreamingContext context) {} 

它加載的數據(基本上,與GetObjectData相反)。據推測,隨着(未經測試):

StreamThisData = (Data)info.GetValue("Object Data", typeof(Data)); 
+0

+1雖然我知道錯過了什麼,如果我能記住解釋,該死!大聲笑 –

+0

你能告訴我一個littel的例子,我不知道它... –

+0

@Jasim你的意思是,就像我的答案中顯示的例子? –